LinQ& DataTable Group by C# [英] LinQ & DataTable Group By Question in C#

查看:539
本文介绍了LinQ& DataTable Group by C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataTable并存储4列(StockCardCode,Explain,Quantity,BranchCode)和Im将其与LinQ进行分组。代码是我使用Group By的关键。当我写我的查询时,我可以在select语句中使用2列,我该如何显示此查询中的所有列?此查询返回2列。我不能在我的查询中使用x.Field(Explain)。

  var query = from in in incoming.AsEnumerable ()
group s by s.Field< string>(Stock card Code)
into grp
orderby grp.Key
select new {StockCardCode = grp.Key,Quantity = grp.Sum(r => r.Field< decimal>(Quantity))};

传入:DataTable

解决方案

由于您是通过StockCardQuote进行分组,因此Explain值将是具有相同StockCardQuote的行的所有解释值 - 它将成为 IEnumerable< T> ,所以如果说是一个字符串,你会得到 IEnumerable< string>



要将其包含在您的选择语句中,只需执行

  select new {
StockCardCode = grp.Key,
Quantity = grp.Sum(r => r。字段< decimal>(Quantity)),
说明= grp.Select(r => r.Field< string>(Explain))};


I have a DataTable and stores 4 columns (StockCardCode,Explain,Quantity,BranchCode), and Im grouping them with a LinQ. Code is my key for using Group By. When I write my query, I just can use 2 columns in select statement, how can I show all columns in this query? This query returns me 2 column. I cant use x.Field("Explain") in my query for example.

var query = from s in incoming.AsEnumerable()
                        group s by s.Field<string>("Stock Card Code")
                            into grp
                            orderby grp.Key
                            select new { StockCardCode = grp.Key, Quantity = grp.Sum(r => r.Field<decimal>("Quantity")) };

incoming: DataTable

解决方案

Since you are grouping by StockCardQuote, the "Explain" value is going to be all of the Explain values from rows with the same StockCardQuote -- it is going to be an IEnumerable<T>, so if Explain is a string, you'll get IEnumerable<string>.

To include this in your select statement, just do

select new { 
    StockCardCode = grp.Key, 
    Quantity = grp.Sum(r => r.Field<decimal>("Quantity")),
    Explanations = grp.Select(r => r.Field<string>("Explain")) };

这篇关于LinQ&amp; DataTable Group by C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆