簡體   English   中英

如何使用Linq將兩個以上的表分組

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

我有三個表(“評分”,“評論”和“用戶”)。 一個評分可以有多個評論。 一則留言屬於一位使用者。

到目前為止,我有這個運行良好的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);

我該如何分組?

這取決於您要分組的內容。 但是有多種解決方案。

解決方案1:

假設您要按評分分組,則可以執行以下操作:

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

這樣,您就可以為每個評分單行。 動態對象g包含每個評分的評論/用戶對列表。

解決方案2:

但是,就像提到的@gertarnold一樣,讀入要分組的對象也更容易。 然后遍歷它的屬性。 像這樣:

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

這很容易理解。 它具有性能下降的困難,因為它對內部循環中的每個注釋執行單獨的數據庫SELECT -statement。 如果一個評分有很多評論,那么這很慢。 第一個帶有分組的示例將所有內容放入一個數據庫SELECT語句中,這要快得多。

解決方案3:

並且有一種方法可以同時兼顧兩者的優點。 像解決方案2一樣進行操作,並在其前面添加一些DataLoadOptions

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

這將在單個SELECT中將所有必需的子對象預加載所有等級。 它既快速又易於閱讀和理解。

PS:附帶說明:表格應以單數命名。 在這種情況下, RatingCommentUser而不是RatingsCommentsUsers

PS2:要在解決方案1中也獲得沒有注釋的評分,則需要將聯接轉換為外部聯接。 像這樣:

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

另請參閱: 101個LINQ樣本-左外部聯接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM