2011-06-14 50 views
1

假設我有以下數據使用LINQ to組,秩序和連接字符串

Key ID  Data 
A  1  Hello 
A  2  World 
B  2  Bar 
B  1  Foo 

我期待產生

A  HelloWorld 
B  FooBar 

我掙扎着爬語法完全正確的結果 - 我試圖使用Aggregate,但我不確定我是否可以(或應該)使用SelectMany

我會很感激任何幫助。

Dim data = result.Rows. 
        GroupBy(Function(r) r.Key). 
        Select(Function(g) g.OrderBy(Function(s) s.ID)). 
        Aggregate(New StringBuilder, Function(cur, nxt)     
           cur.Append(nxt.First.Data)) 

感謝

西蒙

+3

你願意把你的代碼ü達到這麼遠? – 2011-06-14 14:21:10

+0

我的理解是否正確,您希望將同一個鍵的單詞按其ID的順序連接在一起? – 2011-06-14 14:23:02

+0

結果是'DataTable'? – Magnus 2011-06-14 14:25:16

回答

11

我認爲這(C#)應該工作:

var data = from r in result.Rows 
      group r by r.Item("Key").ToString() into g 
      select new { 
       g.Key, 
       Joined = string.Join("", g.OrderBy(s => s.Item("ID")) 
             .Select(s => s.Item("Data"))) 
      }; 
+0

..很多thx。這就說得通了! – 2011-06-14 14:37:54

+0

+1這可能是最乾淨的解決方案。 – 2011-06-14 15:24:58

+0

我正在使用這個(和/或@Bala R),但它沒有引用Data列。什麼是字符串。加入行爲還是以某種方式隱含完成? – 2011-06-14 15:57:33

1
Dim result = result.Rows.GroupBy(Function(r) r.Key).Select(Function(g) New With { _ 
    g.Key, _ 
    String.Join("", g.OrderBy(Function(r) r.ID)) _ 
}) 
+0

啊,我剛剛注意到與其他答案几乎相同的東西。我會離開我的,因爲它是vb.net,它使用方法的語法(如在問題中)。 – 2011-06-14 14:42:34

1

你不想彙總的組。你想要將每個組的元素聚合到自己身上。

如果您想查詢做到這一點,那麼

Dim data = result.Rows 
    .GroupBy() 
    .Select(Function(g) g 
    .OrderBy() 
    .Aggregate() 
    ) 

如果匿名函數開始變得毛髮過多寫,只是使接受一個IGrouping<int, Row>並把它變成你想要的東西的方法。然後調用它像:

Dim data = result.Rows 
    .GroupBy() 
    .Select(myMethod) 
2

下面是一個可選的實現:

var source = new Item[] 
{ 
    new Item { Key = "A", ID = 1, Data = "Hello" }, 
    new Item { Key = "A", ID = 2, Data = "World" }, 
    new Item { Key = "B", ID = 2, Data = "Bar" }, 
    new Item { Key = "B", ID = 1, Data = "Foo" } 
}; 

var results = source 
    .GroupBy(item => item.Key) 
    .Select(group => group 
     .OrderBy(item => item.ID) 
     .Aggregate(new Item(), (result, item) => 
      { 
       result.Key = item.Key; 
       result.Data += item.Data; 
       return result; 
      }));