如果名称相同,我试图弄清楚如何只选择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?)
答案 0 :(得分:2)
BasicInfos = BasicInfos.GroupBy(y => y.Name)
.Select(y => y.OrderBy(z => z.Id).First())
答案 1 :(得分:2)
类似的东西:
BasicInfos = BasicInfos.GroupBy(y => y.Name)
.Select(y => new BasicInfo{ Name = y.Key, Id = y.Min(x => x.Id));
这将为您提供最低密钥的所有名称。
答案 2 :(得分:1)
您可以使用MoreLINQ中的MinBy:
public void enqueue(T queueElement) throws QueueOverflowException
{
答案 3 :(得分:-1)
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)));
如果名称相同,则仅选择ID最低的对象
因此,这只返回重复的内容,如果有重复,则返回id最小的记录。上面的示例将返回2个项目,并忽略那些没有找到重复名称的项目。如果这不正确,那么使用没有where子句的这个版本。
var usersWithSameName = BasicInfos.GroupBy(x => x.Name)
.Select(x => x.Single(y => y.Id == x.Min(z => z.Id)));