如何排序的特定字段在C#中的对象的数组? [英] How to sort an array of object by a specific field in C#?

查看:170
本文介绍了如何排序的特定字段在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???

什么是做这个,而无需编写吨code(如果可能)?

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

排序的原始列表:

Sorting the original list:

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

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

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