如何按 C# 中的特定字段对对象列表进行排序? [英] How to sort a list of objects by a specific field in C#?

查看:22
本文介绍了如何按 C# 中的特定字段对对象列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这门课:

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

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

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?

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

谢谢

推荐答案

使用 LINQ:

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

对原始列表进行排序:

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

这篇关于如何按 C# 中的特定字段对对象列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆