How do you use LINQ to find the duplicate of a specific property?

前端 未结 3 855
夕颜
夕颜 2021-02-11 19:10
Customer customerOne = new Customer(\"John\", \"Doe\");
Customer customerTwo = new Customer(\"Super\", \"Man\");
Customer customerThree = new Customer(\"Crazy\", \"Guy\"         


        
相关标签:
3条回答
  • 2021-02-11 19:26
    var groups = customers.GroupBy(c => c.LastName).Where(g => g.Skip(1).Any());
    foreach(var group in groups) {
        Console.WriteLine(group.Key);
        foreach(var customer in group) {
            Console.WriteLine("\t" + customer.FirstName);
        }
    }
    

    Output:

    Doe
            John
            Jane
    Man
            Super
            Bat
    

    You can flatten the resulting sequence of groups into one sequence with

    var list = groups.SelectMany(g => g);
    
    0 讨论(0)
  • 2021-02-11 19:30
        var result = from c in customers
                     join c2 in customers on c.LastName equals c2.LastName
                     where c != c2
                     select c;
    
    0 讨论(0)
  • 2021-02-11 19:35
     customers.GroupBy(c => c.LastName).Where(g => g.Skip(1).Any()).SelectMany(c => c)
    

    or with LINQ syntax:

            var q = from c in customers
                    group c by c.LastName into g
                    where g.Skip(1).Any()
                    from c in g
                    select c;
    
    0 讨论(0)
提交回复
热议问题