C#Datatable - 使用linq分组多列

时间:2016-10-13 07:02:12

标签: c# linq datatable

我有像这样的数据

| Supplier  | Product | Price1 | Price2 | Price3 | ... | PriceN |
|-----------|---------|--------|--------|--------|-----|--------|
| Supplier1 | Orange  | 100    | 105    | 150    | ... | 180    |
| Supplier1 | Orange  | 110    | 130    | 140    | ... | 180    |
| Supplier2 | Orange  | 200    | 250    | 270    | ... | 350    |
| Supplier2 | Orange  | 250    | 270    | 320    | ... | 270    |

我想将行分组为下一行:

| Supplier  | Product | Price1  | Price2  | Price3  | ... | PriceN  |
|-----------|---------|---------|---------|---------|-----|---------|
| Supplier1 | Orange  | 100-110 | 105-130 | 140-150 | ... | 180     |
| Supplier2 | Orange  | 200-250 | 250-270 | 270-320 | ... | 270-350 |

像“PriceN”这样的列数可以是任意的。 我怎么能用LINQ做到这一点?

4 个答案:

答案 0 :(得分:0)

您可以按SupplierProduct分组为

var result = from x in data
             group x by new { x.Supplier, x.Product }
             select x;

var result = data.GroupBy(x => new { x.Supplier, x.Product });

类似地,您可以在组子句

中使用任意数量的属性

答案 1 :(得分:0)

你必须在另一个lambda表达式中单独分组

result.tolist().GroupBy(p=> p.x,p.x2,p.x3 ...);

答案 2 :(得分:0)

您可以使用GroupByJOIN来连接价格列的值:

var groupedSupplier = supplier.GroupBy(s => new { s.Supplier, s.Product })
                              .Select(supplier => supplier.Supplier, 
                                                  supplier.Product,
                                                  supplier.Price1 = string.Join(",", supplier.Select(x => x.Price1)),
                                                  supplier.Price2 = string.Join(",", supplier.Select(x => x.Price2)),
...);

答案 3 :(得分:0)

要在lambda表达式中按多列分组,请使用:

var groupedSupplier = supplier.GroupBy(s => s.Supplier,
                                       s => s.Product)

有关详细信息,请参见Jon Skeet撰写的“ C#深度”的第11章,第11章“查询表达式和对象的LINQ:11.6分组和延续”,http://csharpindepth.com/

相关问题