多列上的Groupby

时间:2013-11-10 09:32:47

标签: c# sql visual-studio-2010 linq visual-studio

我有一个DataTable,我想将其转换为列表

 var rows = cableDataTable.AsEnumerable()                            
 .Select((x) =>
  new
  {
     TagGroup = x.Field<string>("TagNo"),
     RowNo = (i == 0) ? (j++).ToString() : "",
     TagNo = x.Field<string>("TagNo"),
     FromBayPanel = x.Field<string>("FromBayPanel"),                                     
     Size = x.Field<string>("CoreSize"),
     Type = x.Field<string>("Type"),
     FromBay = x.Field<string>("FromBay"),
     FromPanel = x.Field<string>("FromPanel"),
     CoreNo = x.Field<string>("CoreNo") == DBNull.Value.ToString() ? "" : x.Field<string>("CoreNo"),
     RealCoreNo = x.Field<int>("RealCoreNo"),                                 
     FromDevice = x.Field<string>("FromDevice") == DBNull.Value.ToString() ? "" : x.Field<string>("FromDevice"),                                 
     FromTerminal = x.Field<string>("FromTerminal") == DBNull.Value.ToString() ? "" : x.Field<string>("FromTerminal"),
     FromRef = x.Field<string>("FromRef") == DBNull.Value.ToString() ? "" : x.Field<string>("FromRef"),
     ToBay = x.Field<string>("ToBay"),
     ToPanel = x.Field<string>("ToPanel"),
     ToDevice = x.Field<string>("ToDevice") == DBNull.Value.ToString() ? "" : x.Field<string>("ToDevice"),                                
     ToTerminal = x.Field<string>("ToTerminal") == DBNull.Value.ToString() ? "" : x.Field<string>("ToTerminal"),
     ToRef = x.Field<string>("ToRef") == DBNull.Value.ToString() ? "" : x.Field<string>("ToRef"),
     Remark = x.Field<string>("Remark") == DBNull.Value.ToString() ? "" : x.Field<string>("Remark"),
                             }).ToList();

我想要在多个列上使用DataTable进行分组。但是当我喜欢这个时

1)我该怎么做?

2)还有一个问题是,在SQL Server端(通过isNull命令)或客户端转换DBNull值会更好吗?

2 个答案:

答案 0 :(得分:1)

var resultSet= dataTable.GroupBy(e=> new { e.Column1, e.Column2 });

答案 1 :(得分:1)

在GroupBy之后,你需要使用像sum这样的聚合函数,就像它在sql中一样。

           var resultSet = dataTable.GroupBy(e => new { e.Column1, e.Column2 }).Select(a => new { key1 = a.Key.Column1, Key2 = a.Key.Column2, TotalSize = a.Sum(b => b.Size), ConCatenatedTagGroups  = a.Select(c => c.TagGroup ).Aggregate((d, e) => d + e)});