简体   繁体   English

C#LINQ:我们可以从GroupBy返回相同的实例,而不是重新进行吗?

[英]C# LINQ: Can we return same instance from GroupBy instead of doing new?

I have a collection where I need to group and find max from that group. 我有一个集合,我需要分组并从该分组中查找最大值。 So I did 所以我做了

var foo = foobar.GroupBy(x => x.Name)
                .Select(x => new Foo { Name = x.Key, Version = x.Max(v => v.Version)))
                .ToList();

If there are say more that 2 properties, is it possible to return same object instead of creating new? 如果说两个以上的属性,是否可以返回相同的对象而不是创建新的对象?

Sure, use OrderByDescending on the group and then First to get the max-version-object: 当然, OrderByDescending在该组上使用OrderByDescending ,然后使用First来获取max-version-object:

var maxVersionObjectByName = foobar
    .GroupBy(x => x.Name)
    .Select(grp => grp.OrderByDescending(x => x.Version).First())
    .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM