简体   繁体   English

如何使用Linq将两个以上的表分组

[英]How to group more than two tables using Linq

I have three tables ("Ratings", "Comments" and "Users"). 我有三个表(“评分”,“评论”和“用户”)。 One rating can have multiple comments. 一个评分可以有多个评论。 One comment belongs to one user. 一则留言属于一位使用者。

So far, I have this LINQ statement which is working fine. 到目前为止,我有这个运行良好的LINQ语句。

from rating in Ratings
join comment in Comments
on rating.ID equals comment.RatingID
join user in Users
on comment.UserID equals user.ID
select new {rating, comment, user}
.Where(x => x.rating.LocationID == 3);

How can I group this? 我该如何分组?

It depends a bit on what you want to group by. 这取决于您要分组的内容。 But there a multiple solutions. 但是有多种解决方案。

Solution 1: 解决方案1:

Let's say you would like to group by rating, then you could do: 假设您要按评分分组,则可以执行以下操作:

var query1 = from rating in db.Ratings
                join comment in db.Comments
                    on rating.ID equals comment.RatingID
                join user in db.Users
                    on comment.UserID equals user.ID
                group new { comment, user } by rating into g
                select new { g.Key, l = g.ToList() };

foreach (var row in query1)
{
    // you get rows grouped by rating
    Debug.WriteLine(row.Key.ID); // rating.ID

    // and a list of comments/users per rating
    foreach (var g in row.l)
    {
        Debug.WriteLine(g.comment.ID);
        Debug.WriteLine(g.user.ID);
    }
}

This gives you a single line per rating. 这样,您就可以为每个评分单行。 And the dynamic object g contains a List of comment/user pairs per rating. 动态对象g包含每个评分的评论/用户对列表。

Solution 2: 解决方案2:

However, like @gertarnold mentioned, it's easier to just read in the object you want to group by. 但是,就像提到的@gertarnold一样,读入要分组的对象也更容易。 And then traverse it's properties. 然后遍历它的属性。 Like this: 像这样:

var query2 = db.Ratings;

foreach (var rating in query2)
{
    Debug.WriteLine(rating.name);
    foreach (var comment in rating.Comments)
    {
        Debug.WriteLine(comment.name);
        Debug.WriteLine(comment.User.name);
    }
}

This is a lot easier to comprehend. 这很容易理解。 It has a performance downside tough, because it performs a separate database SELECT -statement for each comment within the inner loop. 它具有性能下降的困难,因为它对内部循环中的每个注释执行单独的数据库SELECT -statement。 If a rating has many many comments, then this is very slow. 如果一个评分有很多评论,那么这很慢。 The first example with the grouping pulls in everything in a single database SELECT statement, which is a lot faster. 第一个带有分组的示例将所有内容放入一个数据库SELECT语句中,这要快得多。

Solution 3: 解决方案3:

And there is a way to have the best of both solutions. 并且有一种方法可以同时兼顾两者的优点。 Do it like in solution 2 and add some DataLoadOptions in front of it: 像解决方案2一样进行操作,并在其前面添加一些DataLoadOptions

DataLoadOptions options = new DataLoadOptions();
options.LoadWith<Rating>(rating => rating.Comments);
options.LoadWith<Comment>(comment => comment.User);
db.LoadOptions = options;

This will preload all ratings with all the necessary child objects in a single SELECT . 这将在单个SELECT中将所有必需的子对象预加载所有等级。 It's fast and easy to read and comprehend. 它既快速又易于阅读和理解。

PS: Just a side note: Tables should be named in singular. PS:附带说明:表格应以单数命名。 In that case Rating , Comment and User instead of Ratings , Comments and Users . 在这种情况下, RatingCommentUser而不是RatingsCommentsUsers

PS2: To get also ratings without comments in solution 1, you need to convert the joins into outer joins. PS2:要在解决方案1中也获得没有注释的评分,则需要将联接转换为外部联接。 Like this: 像这样:

var query1 = from rating in db.Ratings
        join comment in db.Comments
            on rating.ID equals comment.RatingID into j1
        from comment in j1.DefaultIfEmpty()
        join user in db.Users
            on comment.UserID equals user.ID into j2
        from user in j2.DefaultIfEmpty()                                
        group new { comment, user } by rating into g
        select new { g.Key, l = g.ToList() };

see also: 101 LINQ Samples - Left outer join 另请参阅: 101个LINQ样本-左外部联接

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

相关问题 在 datagridviewrow 中按两个以上的值对 Linq 进行分组 - Linq group by more than two 2 values in datagridviewrow 如何使用Linq为SelectMany聚合两个以上的实体? - How to aggregate more than two entities using Linq for a SelectMany? Linq使用SUM和Group By查询两个表 - Linq query for two tables using SUM and Group By 如何在LINQ中对两个以上的表进行外部联接? - How can I do an outer join to more than two tables in LINQ? 如何使用 linq 在 2 个以上的表上使用左连接和非左连接 - How do I use a left-join and non-left-join on more than 2 tables using linq 如何使用外键在LINQ中插入两个以上的表 - How can I insert more than 2 tables in LINQ using foreign keys 在使用Linq的一个查询中,超过1个按组分组的语句 - More than 1 group by statements in one query using Linq 如何在具有两个以上字段的对象上使用Linq返回两个字段? - How can I return two fields using Linq on an object with more than two fields? 如何使用Join with Entity Framework Lambda和Linq在两个或多个表中进行搜索 - How to do a search in two or more tables using Join with Entity framework Lambda and Linq 如何使用asp.net在Single Gridview中合并两个以上的表? 使用.merge方法 - How to merge more than two tables in Single Gridview using asp.net? using .merge method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM