C# 如何迭代分组项并进行比较?

C# 如何迭代分组项并进行比较?,c#,group-by,linq-to-objects,C#,Group By,Linq To Objects,由于我对实体框架还不熟悉,所以我很难使用这种方法。我真的不知道EF是否有什么特别的东西,或者限制是否在我身上 我想对数据库中的一些记录进行分组,然后,我想迭代这些组,然后迭代每个组上的元素,并将其与同一组中的所有其他元素进行比较 我创建了两个简单的类来说明该场景: public class MyContext : DbContext { public DbSet<MyClass> MyClass { get; set; } } 到目前为止,我对上下文注入的了解是: this

由于我对实体框架还不熟悉,所以我很难使用这种方法。我真的不知道EF是否有什么特别的东西,或者限制是否在我身上

我想对数据库中的一些记录进行分组,然后,我想迭代这些组,然后迭代每个组上的元素,并将其与同一组中的所有其他元素进行比较

我创建了两个简单的类来说明该场景:

public class MyContext : DbContext
{
    public DbSet<MyClass> MyClass { get; set; }
}
到目前为止,我对上下文注入的了解是:

this.MyContext.MyClass
            .GroupBy(x => x.Value)
            .ToList() // need to materialize here
            .ForEach(grp =>
            {
                // compare each item with all the other
                // items in the current group        
            });

但是我不知道如何迭代这些项目,然后与同一组中的其他项目进行比较。

通过下面的代码,问题变成了grp是什么类型

grp变量的类型是。该类型派生自IEnumerable,因此每个grp都是一个远程通信列表,因此您可以对grp中的所有项进行访问或执行任何操作

.

您的变量grp是一个iGroup。你可以把它当作一个IEnumerable。例如,您可以获得Id最大的项目,如下所示:

this.MyContext.MyClass
    .GroupBy(x => x.Value)
    .ToList() // need to materialize here
    .ForEach(grp =>
    {
         MyClass itemWithMaxId = grp.FirstOrDefault();
         foreach (MyClass item in grp)
         {
             if (item.Id > itemWithMaxId.Id)
             {
                 itemWithMaxId = item;
             }
         }      
    });
但是请注意,ForEach方法不返回任何内容,它只对列表的每个元素执行指定的操作。如果您想要获得一些东西,例如每个组中Id最大的项目,我建议您使用Linq提供的Select方法,如本例所示:

var itemsWithMaxIdByGroup = this.MyContext.MyClass
    .GroupBy(x => x.Value)
    .ToList() // need to materialize here
    .Select(grp =>
    {
         MyClass itemWithMaxId = grp.First();
         foreach (MyClass item in grp.Skip(1))
         {
             if (item.Id > itemWithMaxId.Id)
             {
                 itemWithMaxId = item;
             }
         }  

         return itemWithMaxId;    
    });

我尝试过两个嵌套的Foreach语句,但我从来没有遇到过这种情况,也从来没有想过三个嵌套的Foreach语句可以执行一些操作。谢谢你的回答,所以我应该做三个嵌套的Foreach语句?这让我心烦意乱,但谢谢,我会试试的。非常感谢你,我用你提供的提琴示例完成了所有工作。在我的例子中,我必须比较同一组中的每个人,所以我只添加了另一个嵌套循环。再次感谢你,工作很有魅力!GroupBy生成的组将始终至少有一个元素。换言之,他们永远不会empty@pinkfloydx33你是对的,我在我的例子中解决了这个问题,谢谢。
this.MyContext.MyClass
    .GroupBy(x => x.Value)
    .ToList() // need to materialize here
    .ForEach(grp =>
    {
         MyClass itemWithMaxId = grp.FirstOrDefault();
         foreach (MyClass item in grp)
         {
             if (item.Id > itemWithMaxId.Id)
             {
                 itemWithMaxId = item;
             }
         }      
    });
var itemsWithMaxIdByGroup = this.MyContext.MyClass
    .GroupBy(x => x.Value)
    .ToList() // need to materialize here
    .Select(grp =>
    {
         MyClass itemWithMaxId = grp.First();
         foreach (MyClass item in grp.Skip(1))
         {
             if (item.Id > itemWithMaxId.Id)
             {
                 itemWithMaxId = item;
             }
         }  

         return itemWithMaxId;    
    });