Linq to SQL和SQL新手的新手。第一篇文章,请温柔 我有类似于下表的内容我正在查询基于C#中日期范围的dataGridView。
1 1 500 8/26/15
1 2 3500 8/26/15
1 3 2200 8/26/15
2 1 2000 8/27/15
2 2 1100 8/27/15
var query = from SU in dct.GetTable<ScrapInCharge>()
where ((SU.DOB >= dateTimePicker2.Value.Date) &&
(SU.DOB <= dateTimePicker1.Value.Date))
orderby SU.HeatNumber descending
select SU;
scrapInChargeBindingSource.DataSource = query;
我需要添加一个列,显示每个ChargeNumber组成的HeatNumber总重量的百分比。我确实想过如何通过HeatNumber获得每次加热的总重量。
var TotalHeatWgt = from a in dct.ScrapInCharges
where ((a.DOB >= dateTimePicker2.Value.Date) &&
(a.DOB <= dateTimePicker1.Value.Date))
group a.Weight by a.HeatNumber
into b
select new { HeatNumber = b.Key, TotalWgt = b.Sum() };
我目前仍然坚持如何将其组合到单个C#查询中,在权重列之后插入%of Heat列。可以这样做,还是需要将未绑定的列添加到Heat的dataGridView%并使用TotalHeatWgt查询的返回值迭代行?
答案 0 :(得分:0)
简单尝试:
var results = data.Select(d => new {
d.HeatNumber,
d.ChargeNumber,
d.Weight,
Percent = 100.0 * d.Weight / data.Where(dd => dd.HeatNumber == d.HeatNumber).Sum(dd => dd.Weight)
});
或
from row in data
select new {
row.HeatNumber,
row.ChargeNumber,
row.Weight,
Percent = 100.0 * row.Weight / (from innerRow in data
where innerRow.HeatNumber == row.HeatNumber
select innerRow.Weight
).Sum()
};
下面的内容将更具性能(至少在内存中,我不确定它在SQL中是否会更好):
var results = data.GroupBy (d => d.HeatNumber)
.SelectMany (grp => grp.Select(row => new {
row.HeatNumber,
row.ChargeNumber,
row.Weight,
Percent = 100.0 * row.Weight / grp.Sum(dd => dd.Weight)
})
);
使用查询语法:
from row in data
group row by row.HeatNumber into grp
from innerRow in grp
select new {
innerRow.HeatNumber,
innerRow.ChargeNumber,
innerRow.Weight,
Percent = 100.0 * innerRow.Weight / grp.Sum(dd => dd.Weight)
};
他们都打印出这个结果:
HeatNumber ChargeNumber Weight Percent
1 1 500 8.06451612903226
1 2 3500 56.4516129032258
1 3 2200 35.4838709677419
2 1 2000 64.5161290322581
2 2 1100 35.4838709677419
这就是你要追求的吗?为简单起见,我省略了按日期过滤,因为实际问题出现在
之后