IT story

사용자 정의 클래스 목록 정렬

hot-time 2020. 8. 5. 07:45
반응형

사용자 정의 클래스 목록 정렬


date속성으로 내 목록을 정렬하고 싶습니다 .

이것은 내 맞춤 클래스입니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Test.Web
{
    public class cTag
    {
        public int id { get; set; }
        public int regnumber { get; set; }
        public string date { get; set; }
    }
}

이것은 List내가 정렬하고 싶은 것입니다 :

List<cTag> Week = new List<cTag>();

내가하고 싶은 date것은 cTag 클래스 속성 별로 목록을 정렬하는 것 입니다. 날짜는 dd.MM.yyyy 형식입니다.

IComparable인터페이스 에 대해 읽었 지만 사용 방법을 모릅니다.


이를 수행하는 한 가지 방법은 delegate

List<cTag> week = new List<cTag>();
// add some stuff to the list
// now sort
week.Sort(delegate(cTag c1, cTag c2) { return c1.date.CompareTo(c2.date); });

cTag 클래스가 IComparable<T>인터페이스 를 구현해야합니다 . 그런 다음 Sort()목록에서 전화하면 됩니다.

IComparable<T>인터페이스 를 구현하려면 CompareTo(T other)메소드 를 구현해야합니다 . 가장 쉬운 방법은 비교하려는 필드의 CompareTo 메서드를 호출하는 것입니다.

public class cTag:IComparable<cTag> {
    public int id { get; set; }
    public int regnumber { get; set; }
    public string date { get; set; }
    public int CompareTo(cTag other) {
        return date.CompareTo(other.date);
    }
}

그러나 날짜를 문자열로 선언했기 때문에 문자열에서 고전적인 정렬을 사용하기 때문에 잘 정렬되지 않습니다. 따라서 클래스를 재정의하고 날짜를 문자열이 아니라 DateTime으로 선언하는 것이 최선의 방법이라고 생각합니다. 코드는 거의 동일하게 유지됩니다.

public class cTag:IComparable<cTag> {
    public int id { get; set; }
    public int regnumber { get; set; }
    public DateTime date { get; set; }
    public int CompareTo(cTag other) {
        return date.CompareTo(other.date);
    }
}

날짜를 포함하는 문자열을 DateTime 유형으로 변환하기 위해 클래스의 인스턴스를 만들 때 수행해야 할 작업 만 DateTime.Parse(String)메소드와 같이 쉽게 수행 할 수 있습니다 .


이 경우 LINQ를 사용하여 정렬 할 수도 있습니다.

week = week.OrderBy(w => DateTime.Parse(w.date)).ToList();

List<cTag> week = new List<cTag>();
week.Sort((x, y) => 
    DateTime.ParseExact(x.date, "dd.MM.yyyy", CultureInfo.InvariantCulture).CompareTo(
    DateTime.ParseExact(y.date, "dd.MM.yyyy", CultureInfo.InvariantCulture))
);

우선 날짜 속성이 날짜를 저장하는 경우 DateTime을 사용하여 저장하십시오. 정렬을 통해 날짜를 구문 분석하면 비교되는 각 항목에 대해 날짜를 구문 분석해야합니다. 매우 효율적이지 않습니다 ...

그런 다음 IComparer를 만들 수 있습니다.

public class TagComparer : IComparer<cTag>
{
    public int Compare(cTag first, cTag second)
    {
        if (first != null && second != null)
        {
            // We can compare both properties.
            return first.date.CompareTo(second.date);
        }

        if (first == null && second == null)
        {
            // We can't compare any properties, so they are essentially equal.
            return 0;
        }

        if (first != null)
        {
            // Only the first instance is not null, so prefer that.
            return -1;
        }

        // Only the second instance is not null, so prefer that.
        return 1;
    }
}

var list = new List<cTag>();
// populate list.

list.Sort(new TagComparer());

대리인으로 할 수도 있습니다.

list.Sort((first, second) =>
          {
              if (first != null && second != null)
                  return first.date.CompareTo(second.date);

              if (first == null && second == null)
                  return 0;

              if (first != null)
                  return -1;

              return 1;
          });

You are right - you need to implement IComparable. To do this, simply declare your class:

public MyClass : IComparable
{
  int IComparable.CompareTo(object obj)
  {
  }
}

In CompareTo, you just implement your custom comparison algorithm (you can use DateTime objects to do this, but just be certain to check the type of "obj" first). For further information, see here and here.


You can use linq:

var q = from tag in Week orderby Convert.ToDateTime(tag.date) select tag;
List<cTag> Sorted = q.ToList()

look at overloaded Sort method of the List class. there are some ways to to it. one of them: your custom class has to implement IComparable interface then you cam use Sort method of the List class.


Thanks for all the fast Answers.

This is my solution:

Week.Sort(delegate(cTag c1, cTag c2) { return DateTime.Parse(c1.date).CompareTo(DateTime.Parse(c2.date)); });

Thanks


YourVariable.Sort((a, b) => a.amount.CompareTo(b.amount));

참고URL : https://stackoverflow.com/questions/3163922/sort-a-custom-class-listt

반응형