linq Group By from DataTable

本文关键字:DataTable from By Group linq | 更新日期: 2023-09-27 18:31:57

我有这样的数据表

谢谢鲍勃·韦尔的帮助

什么是 (选择(X,i) 在你的 linq 中的意思,但是当我在表格中犯了一个错误时我有这个

   No |  Size   | Type   |   FB   |   FP
----------------------------------------
 100  |   2     | typeA  |   FB1  |    A1        
 101  |   3     | typeB  |   FB1  |    A1     
 101  |   4     | typec  |   FB1  |    A1         
 103  |   4     | typeC  |   FB2  |    A2         
 103  |   5     | typeD  |   FB2  |    A2         
 103  |   6     | typeE  |   FB2  |    A2

我想拥有这样的东西

  No |  Size   | Type   |   FB   |   FP    
    ---------------------------------    
100  |  2     | typeA  |   FB1  |    A1    
101  |  3     | typeB  |   FB1  |    A1     
     |  4     | typec  |        |        
103  |  4     | typeC  |   FB2  |    A2         
     |   5    | typeD  |        |        
     |   6    | typeE  |        |   

我该怎么做?我可以使分组依据

var result = from row in cableDataTable.AsEnumerable()
             group row by new 
             {
                 FB = row.Field<string>("FB"),
                 FP = row.Field<string>("FP"), 
                 Size = row.Field<int>("Size"),
                 Type = row.Field<int>("Type"), 
                 no= row.Field<int>("no"),
             } into g
             select new
             {
                 FB = g.Key.FB,
                 FP = g.Key.FP,
                 Size = g.Key.Size,
                 Type = g.Key.Type 

no= g.Key.no };

但它不能给出结果

感谢您的关注

linq Group By from DataTable

这个怎么样:

// First declare a conversion from the DataTable to an anon type
var rows = cableDataTable.AsEnumerable()
                         .Select(x => new { 
                                           Size = x.Field<int>("Size"),
                                           Type= x.Field<string>("Type"),
                                           FB = x.Field<string>("FB"),
                                           FP = x.Field<string>("FP")
                                          });
// Now use group by, ordering and select many to select the rows
var result =  rows.GroupBy (row => new {row.FB, row.FP} )
                  .OrderBy (g => g.Key.FB)
                  .ThenBy(g => g.Key.FP)
                  .SelectMany(g => g.OrderBy(row => row.Size)
                        .Select((x,i) =>
                                               new { 
                                                 Size = x.Size,
                                                 Type = x.Type,
                                                 FB = (i==0) ? x.FB : null,
                                                 FP= (i==0) ? x.FP : null 
                                                }));

您可以将 linq 查询用作 var result = cableDataTable.AsEnumerable()。GroupBy(g => new { g.FB, g.FP}).选择(x => x);