C#Linq按对象分组 [英] C# Linq Group by Object

查看:44
本文介绍了C#Linq按对象分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在LINQ to SQL语句中使用group by有一个问题.

I have an issue of using group by in LINQ to SQL statement.

我的鳕鱼是

var combinedItems = (from article in articles
                     join author in authors
                     on article.AuthorId equals author.Id into tempAuthors
                     from tempAuthor in tempAuthors.DefaultIfEmpty()
                     select new { article , author = tempAuthor});

var groups1 = (from combinedItem in combinedItems
               group combinedItem by combinedItem.article into g
               select g.Key).ToList();

var groups2 = (from combinedItem in combinedItems
               group combinedItem by combinedItem.article.Id into g
               select g.Key).ToList();

我试图用两种不同的方式进行分组.第一种方法是按一个对象分组,第二种方法是按一个对象中的字段分组.

I tried to group in two different ways. The first way, I group by an object and the second way I just group by a field in one of the objects.

当我运行 groups1 时,出现一个错误,要求在客户端进行评估,而当我使用 groups2 时,一切正常.我可以问可能有什么问题吗?如果我想按对象分组,有什么办法吗?

When I run groups1, I got an error saying need to evaluate in client side, while when I use groups2, it works all good. Can I ask what could be wrong? If I want to group by object, is there any way to do it?

推荐答案

如果要按对象分组,因为您没有覆盖 Equals GetHashCode()在您的 Article 类中或已实现的

In case you want to group by object, as you've not overridden Equals and GetHashCode() in your Article class or implemented IEqualityComparer<Article> you're just getting the default comparison, which checks if the references are equal. So what you need is something like this:

class GroupItemComparer : IEqualityComparer<Article>
{

    public bool Equals(Article x, Article y)
    {
        return x.Id == y.Id &&
            x.Name == y.Name;
    }

    public int GetHashCode(Article obj)
    {
        return obj.Id.GetHashCode() ^
            obj.Name.GetHashCode();
    }
}

然后您需要将查询更改为lambda表达式:

And then you need to change your query to lambda expression:

var groups1 = combinedItems.GroupBy(c => c.article , new GroupItemComparer())
                           .Select(c => c.Key).ToList();

如果在将方法转换为SQL方面遇到任何例外情况,则可以在 GroupBy 方法之前使用 AsEnumerable ToList 方法,这种方法在加载数据后,将对内存中已有的数据使用Linq to Objects进行任何进一步的操作.

In case you got any exception regarding translation your method to SQL, you can use AsEnumerable or ToList methods before your GroupBy method, with this methods after data is loaded, any further operation is performed using Linq to Objects, on the data already in memory.

这篇关于C#Linq按对象分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆