C#Linq to Sql group by无法被宣扬

问题描述 投票:0回答:1

嗨,我在Linq to Sql语句中使用group by有一个问题。

我有鳕鱼

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

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

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

c# linq-to-sql
1个回答
0
投票
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表达式:

var groups1 = combinedItems.GroupBy(c => c.article , new GroupItemComparer())
     .Select(c => c.Key).ToList();
© www.soinside.com 2019 - 2024. All rights reserved.