如何按 C# 中的特定字段对对象列表进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1301822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:53:52  来源:igfitidea点击:

How to sort a list of objects by a specific field in C#?

c#sorting

提问by marcgg

I have this class:

我有这门课:

public class StatInfo
{
  public string contact;
  public DateTime date;
  public string action;
}

then I have a list of StatInfo, but I'm not sure how to sort it according to the date field. Should I use the sort method? Should I create my own?

然后我有一个 StatInfo 列表,但我不确定如何根据日期字段对其进行排序。我应该使用排序方法吗?我应该创建自己的吗?

var _allStatInfo = new List<StatInfo>();
// adding lots of stuff in it
_allStatInfo.SortByDate???

What is the best way of doing this without having to write tons of code (if possible)?

无需编写大量代码(如果可能),这样做的最佳方法是什么?

Thanks

谢谢

采纳答案by Ben M

Using LINQ:

使用 LINQ:

var sortedList = _allStatInfo.OrderBy(si => si.date).ToList();

Sorting the original list:

对原始列表进行排序:

_allStatInfo.Sort(new Comparison<StatInfo>((x, y) => DateTime.Compare(x.date, y.date)));

回答by Cecil Has a Name

Use a lambda expression to map a pair to a comparison:

使用 lambda 表达式将一对映射到比较:

_allStatInfo.Sort((x, y) => x.date - y.date);

回答by TruthStands

For a DateTime there shouldn't be a need to compare.

对于 DateTime ,应该不需要比较。

_allStatInfo.OrderyBy(d => d.date);

or

或者

_allStatInfo.OrderByDescending(d => d.Date);

回答by Dan Tao

To illustrate Robert C. Cartaino's answer:

为了说明 Robert C. Cartaino 的回答:

public class StatInfo : IComparable<StatInfo>
{
    public string contact;
    public DateTime date;
    public string action;

    public int CompareTo(StatInfo value)
    {
        return this.date.CompareTo(value.date);
    }
}

var _allStatInfo = new List<StatInfo>();

// this now sorts by date
_allStatInfo.Sort();

Not the most general solution but good if you're only going to sort by date. And, as Robert said, you can still always override the default sort by passing an IComparer parameter to the sort method.

不是最通用的解决方案,但如果您只想按日期排序,则很好。而且,正如 Robert 所说,您仍然可以通过将 IComparer 参数传递给 sort 方法来覆盖默认排序。

回答by Jon Skeet

I see you've got the answer anyway, but...

我看你已经得到了答案,但是......

  1. You can avoid some ugliness by just splitting the statement into two halves:

    Comparison<StatInfo> comparison = (x, y) => DateTime.Compare(x.date, y.date);
    _allStatInfo.Sort(comparison);
    

    You might want to consider just calling CompareTodirectly, too:

    Comparison<StatInfo> comparison = (x, y) => x.date.CompareTo(y.date);
    _allStatInfo.Sort(comparison);
    
  2. You could create an IComparer<T>implementation using my ProjectionComparerclass - it's part of MiscUtil, and I've included an uncommented version at the bottom of this answer. You'd then write:

    _allStatInfo.Sort(ProjectionComparer<StatInfo>.Create(x => x.date));
    
  3. Even if you're using .NET 2.0, you can still use LINQ by way of LINQBridge.

  1. 您可以通过将语句分成两半来避免一些丑陋:

    Comparison<StatInfo> comparison = (x, y) => DateTime.Compare(x.date, y.date);
    _allStatInfo.Sort(comparison);
    

    您可能也想考虑直接调用CompareTo

    Comparison<StatInfo> comparison = (x, y) => x.date.CompareTo(y.date);
    _allStatInfo.Sort(comparison);
    
  2. 您可以IComparer<T>使用我的ProjectionComparer类创建一个实现- 它是MiscUtil的一部分,我在此答案的底部包含了一个未注释的版本。然后你会写:

    _allStatInfo.Sort(ProjectionComparer<StatInfo>.Create(x => x.date));
    
  3. 即使您使用 .NET 2.0,您仍然可以通过LINQBridge使用 LINQ 。

Here's the ProjectionComparerclass required for the second answer. The first couple of classes are really just helpers to let generic type inference work better.

这是ProjectionComparer第二个答案所需的课程。前几个类实际上只是让泛型类型推断更好地工作的助手。

public static class ProjectionComparer
{
    public static ProjectionComparer<TSource, TKey> Create<TSource, TKey>
        (Func<TSource, TKey> projection)
    {
        return new ProjectionComparer<TSource, TKey>(projection);
    }

    public static ProjectionComparer<TSource, TKey> Create<TSource, TKey>
        (TSource ignored, Func<TSource, TKey> projection)
    {
        return new ProjectionComparer<TSource, TKey>(projection);
    }

}

public static class ProjectionComparer<TSource>
{
    public static ProjectionComparer<TSource, TKey> Create<TKey>
        (Func<TSource, TKey> projection)
    {
        return new ProjectionComparer<TSource, TKey>(projection);
    }
}

public class ProjectionComparer<TSource, TKey> : IComparer<TSource>
{
    readonly Func<TSource, TKey> projection;
    readonly IComparer<TKey> comparer;

    public ProjectionComparer(Func<TSource, TKey> projection)
        : this (projection, null)
    {
    }

    public ProjectionComparer(Func<TSource, TKey> projection,
                              IComparer<TKey> comparer)
    {
        projection.ThrowIfNull("projection");
        this.comparer = comparer ?? Comparer<TKey>.Default;
        this.projection = projection;
    }

    public int Compare(TSource x, TSource y)
    {
        // Don't want to project from nullity
        if (x==null && y==null)
        {
            return 0;
        }
        if (x==null)
        {
            return -1;
        }
        if (y==null)
        {
            return 1;
        }
        return comparer.Compare(projection(x), projection(y));
    }
}

回答by Mina

it worked for me ?Sorting array of custom type using delegate

它对我有用吗?使用委托对自定义类型的数组进行排序

// sort array by name
Array.Sort(users, delegate(User user1, User user2) 
           {
             return user1.Name.CompareTo(user2.Name);
           });
// write array (output: Betty23 Lisa25 Susan20)
foreach (User user in users) Console.Write(user.Name + user.Age + " ");