简体   繁体   English

LINQ GroupBy-按名称选择最低ID组

[英]LINQ GroupBy - Select lowest ID group by name

I am trying to figure out how to select only the object with the lowest ID if the Name is the same: 我试图弄清楚如果名称相同,如何仅选择ID最低的对象:

public class BasicInfo
{
    public int Id {get;set;}
    public string Name {get; set;}
}

List<BasicInfo> BasicInfos = new List<BasicInfo>();
BasicInfos.Add(new BasicInfo() { Id = 1, Name = "John" });
BasicInfos.Add(new BasicInfo() { Id = 2, Name = "John" });

BasicInfos = BasicInfos.GroupBy(y => y.Name)...(What goes here?)
BasicInfos = BasicInfos.GroupBy(y => y.Name)
    .Select(y => y.OrderBy(z => z.Id).First())

Something like that : 像这样:

BasicInfos = BasicInfos.GroupBy(y => y.Name)
                       .Select(y => new BasicInfo{ Name = y.Key, Id = y.Min(x => x.Id));

This will give you all names with the lowest key. 这将为您提供所有具有最低键的名称。

You can use MinBy from MoreLINQ : 您可以从MoreLINQ使用MinBy

var lowestIDsByName = BasicInfos.GroupBy(bi => bi.Name)
    .Select(g => g.MinBy(bi => bi.Id))
    .ToList();
List<BasicInfo> BasicInfos = new List<BasicInfo>();
BasicInfos.Add(new BasicInfo() { Id = 1, Name = "John" });
BasicInfos.Add(new BasicInfo() { Id = 2, Name = "John" });
BasicInfos.Add(new BasicInfo() { Id = 3, Name = "Sam" });
BasicInfos.Add(new BasicInfo() { Id = 4, Name = "Sam" });
BasicInfos.Add(new BasicInfo() { Id = 5, Name = "Igor" });
BasicInfos.Add(new BasicInfo() { Id = 6, Name = "joei" });

var usersWithSameName = BasicInfos.GroupBy(x => x.Name)
    .Where(x => x.Count() > 1)
    .Select(x => x.Single(y => y.Id == x.Min(z => z.Id)));

select only the object with the lowest ID if the Name is the same 如果名称相同,则仅选择ID最低的对象

So this returns just those where this a duplicate and if there is a duplicate then it returns the record with the smallest id. 因此,这将仅返回重复项,如果存在重复项,则返回具有最小ID的记录。 The above example would return 2 items and ignore those where no duplicate name could be found. 上面的示例将返回2个项目,并忽略那些找不到重复名称的项目。 If that is not correct then use this version without the where clause. 如果那是不正确的,则使用不带where子句的该版本。

var usersWithSameName = BasicInfos.GroupBy(x => x.Name)
    .Select(x => x.Single(y => y.Id == x.Min(z => z.Id)));

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

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