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

查看:475
本文介绍了如何在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天全站免登陆