如何按两个字段分组并返回匹配的原始对象?

时间:2016-03-21 21:09:07

标签: linq group-by

任何人都可以告诉我,在这些尝试通过Linq找到重复的名字和姓氏时我会搞砸了什么?

//尝试1

var  duplicateName =  
    from o in people
    from x in people 
    group o by new { Last= x.LastName?.Trim()?.ToUpperInvariant(),  First=x.FirstName?.Trim()?.ToUpperInvariant() }
    into g
    where g.Count() > 1
    select g; 

//尝试2

var  duplicateName =  
        people.GroupBy(x => new { Last= x.LastName?.Trim()?.ToUpperInvariant(),  First=x.FirstName?.Trim()?.ToUpperInvariant() })
        .Where(g=> g.Count() > 1) 
        .Select(y => y)
        .ToList() ;

1 个答案:

答案 0 :(得分:1)

第二次尝试几乎就是你想要的。但是你选择了分组。如果要选择分组中的对象,则应使用SelectMany

var  duplicateName =  
        people.GroupBy(x => new { Last= x.LastName?.Trim()?.ToUpperInvariant(),  First=x.FirstName?.Trim()?.ToUpperInvariant() })
        .Where(g=> g.Count() > 1) 
        .SelectMany(y => y)
        .ToList() ;
相关问题