LINQ group by和combine as CSV

时间:2011-02-24 13:07:11

标签: c# linq

这就是我所拥有的

ID Value
1  Val1
1  Val2
3  Val3   
3  Val4
4  Val5

我需要

ID Value
1  Val1, Val2
3  Val3, Val4
5  Val4

我被困在这一点上:

      var groups = Result.GroupBy(res => res.ID);      
      foreach (var group in groups)
      {                       
        foreach (var entry in group)
        {

        }
       }

如何将结果转换为新的匿名类型?

注意,我还需要一个可以序列化的具体类型。

编辑:最终解决方案就像

[Serializable]   
public class KeyValueCSV 
{
    public decimal Key { get;set;}
    public string CSVValues { get;set;}
}

List<KeyValueCSV> kvCSVList = new List<KeyValueCSV>();
KeyValueCSV kvCSV;

          var groups = Result.GroupBy(res => res.ID);      
          foreach (var group in groups)
          {  kvCSV = new KeyValueCSV();  
            foreach (var entry in group)
            {
               kvCSV.id = entry.id;
               kv.CSVValues = enrty.Value + ", ";
            }
           kvCSVList.Add(kvCSV);
           }

2 个答案:

答案 0 :(得分:4)

集团拥有您需要的一切

[Serializable]   
public class KeyValueCSV 
{
    public string Key { get;set;}
    public List<string> CSVValues { get;set;}
}

 var groups = 
       Result.GroupBy(res => res.ID)
       .Select(x => new KeyValueCSV() { 
            Key=x.key, 
            CSVValues= string.Join(",", x.ToList()) 
           }
       );

您也可以这样做:

var groups = (
from res in Result
group r by res.ID
into grouping

select
   new  KeyValueCSV()
   {
     Key =  grouping.Key,
     CSVValues=  string.Join(",", grouping.ToList())
   }
);

**如果我搞砸了,请告诉我;)我最近一直在python世界,所以我可能设法混淆了一些sytax ...

答案 1 :(得分:1)

如果你正在做Linq to Objects,你可以这样做

from res in Result
group res by res.ID into grouping
select new
{
 ID = grouping.Key,
 Values = grouping.Select(r => r.Value).Aggregate((a,b) => a + ", " + b)
}