如何使用LINQ查找特定属性的副本?

2wnc66cl  于 2023-09-28  发布在  其他
关注(0)|答案(4)|浏览(115)
Customer customerOne = new Customer("John", "Doe");
Customer customerTwo = new Customer("Super", "Man");
Customer customerThree = new Customer("Crazy", "Guy");
Customer customerFour = new Customer("Jane", "Doe");
Customer customerFive = new Customer("Bat", "Man");

List<Customer> customers = new List<Customer>();
customers.Add(customerOne);
customers.Add(customerTwo);
customers.Add(customerThree);
customers.Add(customerFour);
customers.Add(customerFive);

什么LINQ查询将返回一个枚举的所有客户具有相同的姓氏?
结果应包括以下一个示例:无名氏、无名氏、超人和 bat 侠

w8rqjzmb

w8rqjzmb1#

重新配制:您希望按姓氏对客户列表进行分组,筛选出具有多个元素的组,然后选择每个组的每个示例。你几乎可以把这句话逐字翻译成C#:

customers
    .GroupBy(customer => customer.LastName)
    .Where(sameLastName => sameLastName.Skip(1).Any())
    .SelectMany(customer => customer)

或者使用LINQ语法:

var q = from customer in customers
        group customer by customer.LastName into sameLastName
        where sameLastName.Skip(1).Any()
        from customer in sameLastName
        select customer;
nwlqm0z1

nwlqm0z12#

var result = from c in customers
                 join c2 in customers on c.LastName equals c2.LastName
                 where c != c2
                 select c;
llmtgqce

llmtgqce3#

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);
    }
}

输出量:

Doe
        John
        Jane
Man
        Super
        Bat

您可以使用以下命令将生成的组序列展平为一个序列

var list = groups.SelectMany(g => g);
lnvxswe2

lnvxswe24#

如果你只是想找到是否有重复,你可以使用这个技巧。

var result = customers.GroupBy(c => c.Id).Count() != customers.Count();

相关问题