2011-12-21 91 views
1

我是LINQ的新手。我堅持一個非常愚蠢的問題LINQ中的聚合

Name Subjects Role 
---- -------- -------- 

A  Math  Student 
A  English  Student 
B  Math  Student 
B  English  Student 
C  Math  Student 
C  Math  Admin 

我需要得到作爲

Name Subjects  Role 
---- --------  -------- 
A  Math, English Student 
B  Math, English Student 
C  Math   Student 
C  Math   Admin 

我很困惑,如何去了解這個問題。這在SQL中很簡單,我可以通過函數來​​執行groupby子句並通過逗號分隔值。

有人可以幫我嗎?

編輯:三列來自3個不同的來源。我更新了結果表。感謝您的幫助!

回答

1

試試這個:

var grouped = classes.GroupBy(g => new {Name = g.Name, Role = g.Role}).Select(
    s => 
    new 
     { 
      Name = s.Key, 
      Subjects = s.Select(x => x.Subject).Aggregate("", (current, se) => current + (", " + se)), 
      Role = s.Select(x => x.Role).First() 
     }); 

var result = grouped.Select(s => new 
            { 
             s.Name, 
             Subjects = s.Subjects.Substring(2), 
             s.Role 
            }).ToList(); 

這將會把你的科目以逗號分隔字符串。

希望這會有所幫助。

+0

如果角色不同,那麼? – whihathac 2011-12-21 12:06:02

+0

你需要在多列上做一個「GroupBy」。我已經更新了代碼,請現在檢查 – 2011-12-21 12:23:41

+0

謝謝@Abdul。我正在使用LINQ to Entity,當我在LINQ PAD上執行時遇到此錯誤 NotSupportedException:LINQ to Entities無法識別方法'System.String Aggregate [String,String](System.Collections.Generic.IEnumerable' 1 [System.String],System.String,System.Func'3 [System.String,System.String,System.String])'方法,並且此方法不能轉換爲存儲表達式。 – whihathac 2011-12-22 11:16:16

2

我沒有你的代碼,但它應該是這樣的:

var grouped = from element in yourList 
       group element by element.Name into g 
       select new 
       { 
        Name = g.Key, 
        Subjects = g.Select(e => e.Subject), 
        // Assuming they are identical when they have the same name 
        Role = g.First().Role 
       }; 
+0

如果角色不相同,那麼? – whihathac 2011-12-21 12:05:52

+0

@whihathac然後我必須知道你的期望。如果你期望一系列角色,然後用'g.Select(e => e.Role)'交換'g.First()。Role'。另外,如果你想把它作爲一個逗號分隔的字符串,那麼在本地使用'string.Join',或者如其他答案'Aggregate'所述。 – 2011-12-21 13:35:00

+0

@whihathac我沒有看足夠長的結果表。阿卜杜爾提到使用多個分組。 – 2011-12-21 13:38:47