我有MyClass类型:
MyClass
{
public string Name { get;set; }
public string LastName { get;set; }
}
我也得到了我的收藏:
List<MyClass> _Lst = new List<MyClass>();
我添加了一些条目,像这样:
乌利希期刊指南:
_Lst.Add(new MyClass{Name = "Petya" , LastName = "sergeevi4"};
_Lst.Add(new MyClass{Name = "Vasya" , LastName = "petrovi4"};
_Lst.Add(new MyClass{Name = "Igori" , LastName = "alibertovi4"};
_Lst.Add(new MyClass{Name = "Vasya" , LastName = "iakubovi4"};
_Lst.Add(new MyClass{Name = "Vasya" , LastName = "ianukovi4"};
那么我如何排序(降序)我的集合通过Lambda表达式得到这样的东西:
_Lst[0] = Name = "Vasya" , LastName = "iakubovi4"; //Where [n] - just index of mylist;
_Lst[1] = Name = "Vasya" , LastName = "petrovi4";
_Lst[2] = Name = "Vasya" , LastName = "ianukovi4";
_Lst[3] = Name = "Petya" , LastName = "sergeevi4";
_Lst[4] = Name = "Igori" , LastName = "alibertovi4";
目前我正在做这样的事情:
var NewList = _Lst.OrderByDescending(x => x.Name.Count());
GroupBy
方法完全符合您的要求。组是一个带有键(在本例中是一个名称)的集合。您可以命令分组,然后使用SelectMany
:
var newList = _Lst.GroupBy(m => m.Name)
.OrderByDescending(g => g.Count())
.SelectMany(g => g)
.ToList();
一个建议:最好使用ToArray()
而不是ToList()
,因为产生的集合是不可变的,并且不能在事后修改,这会在代码的其他地方引起棘手的错误。
按名字匹配顺序排序后,您可能希望按姓氏的字母顺序排序。同样,这很容易,因为每个组都是一个集合。你可以在你的链上添加一个Select
来实现这个目标:
var newList = _Lst.GroupBy(m => m.Name)
.OrderByDescending(g => g.Count())
.Select(g => g.OrderBy(m => m.LastName))
.SelectMany(g => g)
.ToList();
List<MyClass> _Lst = new List<MyClass>();
_Lst.Add(new MyClass { Name = "Vasya", LastName = "iakubovi4" });
_Lst.Add(new MyClass { Name = "Vasya", LastName = "petrovi4" });
_Lst.Add(new MyClass { Name = "Vasya", LastName = "ianukovi4" });
_Lst.Add(new MyClass { Name = "Petya", LastName = "sergeevi4" });
_Lst.Add(new MyClass { Name = "Igori", LastName = "alibertovi4" });
var result = _Lst.GroupBy(m => m.Name).OrderByDescending(x => x.Count()).SelectMany(x => x).ToList();
把你的代码改成,
var NewList = _Lst.OrderByDescending(x => x.Name);