排序自定义类列表。

时间:2022-09-29 07:37:27

I would like to sort my list with the date property.

我想用日期属性来排序我的列表。

This is my custom class:

这是我的定制课程:

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; }
    }
}

An this is the List that i want sort:

这是我要排序的列表:

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

What I want to do is sort the List by the date property of the cTag class. The date ist in the format: dd.MM.yyyy.

我要做的是按cTag类的日期属性对列表进行排序。格式:dd.mm.yyy。

I read something about the IComparable interface, but don't know how to use it.

我读了一些关于icom寓言的界面,但不知道如何使用它。

10 个解决方案

#1


119  

One way to do this is with a 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); });

#2


43  

You are correct that your cTag class must implement IComparable<T> interface. Then you can just call Sort() on your list.

您是正确的,您的cTag类必须实现icom寓言 接口。然后您可以在列表中调用Sort()。

To implement IComparable<T> interface, you must implement CompareTo(T other) method. The easiest way to do this is to call CompareTo method of the field you want to compare, which in your case is date.

为了实现icom寓言 接口,您必须实现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);
    }
}

However, this wouldn't sort well, because this would use classic sorting on strings (since you declared date as string). So I think the best think to do would be to redefine the class and to declare date not as string, but as DateTime. The code would stay almost the same:

但是,这不会很好,因为这将使用字符串的经典排序(因为您声明日期为string)。所以我认为最好的方法是重新定义类并声明日期不是字符串,而是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);
    }
}

Only thing you'd have to do when creating the instance of the class to convert your string containing the date into DateTime type, but it can be done easily e.g. by DateTime.Parse(String) method.

在创建类的实例以将包含日期的字符串转换为DateTime类型时,您只需要做的事情,但是它可以很容易地完成,例如DateTime.Parse(string)方法。

#3


32  

For this case you can also sort using LINQ:

对于这种情况,你也可以使用LINQ:

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

#4


10  

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))
);

#5


5  

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

你是对的——你需要实施icom寓言。要做到这一点,只需声明您的类:

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.

在CompareTo中,您只需要实现自定义的比较算法(您可以使用DateTime对象来完成此操作,但是要确保首先检查“obj”的类型)。有关进一步的信息,请参见这里和这里。

#6


5  

You can use linq:

您可以使用linq:

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

#7


5  

First things first, if the date property is storing a date, store it using a DateTime. If you parse the date through the sort you have to parse it for each item being compared, that's not very efficient...

首先,如果date属性存储日期,则使用DateTime存储它。如果您通过排序来解析日期,则需要对每个被比较的项目进行解析,这不是非常有效的……

You can then make an IComparer:

你可以做一个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());

You can even do it as a delegate:

你甚至可以把它作为委托来做:

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;
          });

#8


3  

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.

查看列表类的重载排序方法。有一些方法可以做到。其中一个:您的自定义类必须实现icom寓言接口,然后使用列表类的Sort方法。

#9


2  

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

谢谢

#10


0  

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

YourVariable。排序((a,b)= > a.amount.CompareTo(b.amount));

#1


119  

One way to do this is with a 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); });

#2


43  

You are correct that your cTag class must implement IComparable<T> interface. Then you can just call Sort() on your list.

您是正确的,您的cTag类必须实现icom寓言 接口。然后您可以在列表中调用Sort()。

To implement IComparable<T> interface, you must implement CompareTo(T other) method. The easiest way to do this is to call CompareTo method of the field you want to compare, which in your case is date.

为了实现icom寓言 接口,您必须实现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);
    }
}

However, this wouldn't sort well, because this would use classic sorting on strings (since you declared date as string). So I think the best think to do would be to redefine the class and to declare date not as string, but as DateTime. The code would stay almost the same:

但是,这不会很好,因为这将使用字符串的经典排序(因为您声明日期为string)。所以我认为最好的方法是重新定义类并声明日期不是字符串,而是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);
    }
}

Only thing you'd have to do when creating the instance of the class to convert your string containing the date into DateTime type, but it can be done easily e.g. by DateTime.Parse(String) method.

在创建类的实例以将包含日期的字符串转换为DateTime类型时,您只需要做的事情,但是它可以很容易地完成,例如DateTime.Parse(string)方法。

#3


32  

For this case you can also sort using LINQ:

对于这种情况,你也可以使用LINQ:

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

#4


10  

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))
);

#5


5  

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

你是对的——你需要实施icom寓言。要做到这一点,只需声明您的类:

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.

在CompareTo中,您只需要实现自定义的比较算法(您可以使用DateTime对象来完成此操作,但是要确保首先检查“obj”的类型)。有关进一步的信息,请参见这里和这里。

#6


5  

You can use linq:

您可以使用linq:

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

#7


5  

First things first, if the date property is storing a date, store it using a DateTime. If you parse the date through the sort you have to parse it for each item being compared, that's not very efficient...

首先,如果date属性存储日期,则使用DateTime存储它。如果您通过排序来解析日期,则需要对每个被比较的项目进行解析,这不是非常有效的……

You can then make an IComparer:

你可以做一个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());

You can even do it as a delegate:

你甚至可以把它作为委托来做:

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;
          });

#8


3  

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.

查看列表类的重载排序方法。有一些方法可以做到。其中一个:您的自定义类必须实现icom寓言接口,然后使用列表类的Sort方法。

#9


2  

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

谢谢

#10


0  

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

YourVariable。排序((a,b)= > a.amount.CompareTo(b.amount));