简体   繁体   English

Linq Group by在lambda表达式中

[英]Linq Group by in lambda expression

I have Model follow list: 我有Model关注列表:

    Id                  Name
----------------------------------------------------
    1                   john
    1                   john
    1                   john
    2                   jennifer
    2                   jennifer
    3                   smith

I want to group that Model to show following result 我想将该Model分组以显示以下结果

    Id                  Name
----------------------------------------------------
    1                   john
    2                   jennifer
    3                   smith

If Model implements IEquatable<Model> then it's trivial: 如果Model实现IEquatable<Model>那么它是微不足道的:

var noDuplicates = list.Distinct();

If it does not make sense for Model to implement that interface, you can use this overload of Distinct that lets you specify the equality criteria on the side. 如果对于Model ,实现该接口没有意义,则可以使用Distinct 此重载 ,让您在一侧指定相等条件。 The documentation for IEqualityComparer<T> has an example on how to implement such. IEqualityComparer<T>的文档提供了有关如何实现此示例的示例。

                ILookup<int, string> lookup =
                list
                .ToLookup(p => p.Id,
                          p => p.Name);

            foreach (IGrouping<int, string> group in lookup)
            {
                Console.WriteLine(group.Key);
                foreach (string name in group)
                    Console.WriteLine("    {0}", name);
            }

从模型组v中的v通过v.id到g选择g

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

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