通过嵌套列表进行OrderBy列表 [英] OrderBy list by a nested list
问题描述
我有一个objectA列表,每个列表都包含另一个objectB列表.我正在尝试使用(int)ID对每个objectB列表进行排序:
I have a objectA list, each one contain an another objectB list. I'm trying to OrderBy each objectB list with an (int) Id :
var sorted = objectA.OrderBy(a => a.ObjectB.OrderBy(b => b.Id)).ToList();
当然,这是行不通的.有人有建议吗?
Of course, this doesn't work. Someone have an advice ?
推荐答案
如果你想对每个 ObjectB
列表进行排序(即修改它),那么只需使用 Comparison<T>
代表:
If you want to sort each ObjectB
list in place (i.e. modify it), then simply use the List<T>.Sort
method. You will need to specify a custom Comparison<T>
delegate:
foreach (var a in objectA)
{
a.ObjectB.Sort((x, y) => x.Id - y.Id)
}
如果 objectA
是 List< ObjectA>
,则可以使用
If objectA
is a List<ObjectA>
, then you can use the ForEach
method and pass a delegate:
objectA.ForEach(a => a.ObjectB.Sort((x, y) => x.Id - y.Id));
如果您不想修改原始的 ObjectA
实例,则必须将每个 ObjectA
实例投影到一个新实例中(通过克隆它),然后分配排序后的 ObjectB
列表.看起来像(假设所有属性都有公共设置器):
If you don't want to modify your original ObjectA
instances, then you will have to project each ObjectA
instance into a new instance (by cloning it) and then assign sorted ObjectB
lists. It would look something like (presuming that all properties have public setters):
var newList = objectA
.Select(x => new ObjectA()
{
Id = x.Id,
SomethingElse = x.SomethingElse,
ObjectB = x.ObjectB.OrderBy(b => b.Id).ToList()
})
.ToList();
这篇关于通过嵌套列表进行OrderBy列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!