2010-07-13 28 views
5

我想要分組的值的第三列「項目」。用linq獲取分組逗號分隔值

Dictionary<string, int> dic = new Dictionary<string, int>(); 
dic.Add("a", 1); 
dic.Add("b", 1); 
dic.Add("c", 2); 
dic.Add("d", 3); 

var dCounts = 
    (from i in dic 
    group i by i.Value into g 
    select new { g.Key, count = g.Count()}); 

    var a = dCounts.Where(c => c.count>1); 

dCounts.Dump(); 
a.Dump(); 

該代碼產生:

Key Count 
1 2 
2 1 
3 1 

我想這些結果:

Key Count Items 
1 2  a, b 
2 1  c 
3 1  d 

回答

8
​​

使用string.Join(",", {array}),通過你的按鍵陣列英寸

+0

如果我們使用string.Join,那麼像Linq這樣的異常無法識別string.Join方法 – reddy39 2017-12-01 11:00:40

1

您可以使用:

var dCounts = 
    from i in dic 
    group i by i.Value into g 
    select new { g.Key, Count = g.Count(), Values = g }; 

結果產生的分組(價值g)有一個prope rty Key給你的關鍵,但它也實現了IEnumerable<T>,允許您訪問組中的單個值。如果您只返回g,那麼您可以使用foreach迭代所有值或使用LINQ處理它們。

下面是一個簡單的轉儲功能證明這一點:

foreach(var el in dCounts) { 
    Console.Write(" - {0}, count: {1}, values:", el.Key, el.Count); 
    foreach(var item in el.Values) Console.Write("{0}, ", item); 
| 
0
from i in dic 
group i.Key by i.Value into g 
select new 
{ 
    g.Key, 
    count = g.Count(), 
    items = string.Join(",", g.ToArray()) 
});