我的查询如下
var result = from cr in cumulativeresult
orderby cr.Days
select new
{
Days = cr.Days,
Com = (from cr1 in cumulativeresult
where cr1.Days < cr.Days
group cr1 by 1 into cr1grp
select
new
{
Count = cr1grp.Count() + cr.Com
}),
ComPercent = Math.Round((double.Parse((
from cr1 in cumulativeresult
where cr1.Days < cr.Days
group cr1 by 1 into cr1grp
select cr1grp.Count() + cr.Com).ToString()) / ComCount) * 100, 2)
};
Run Code Online (Sandbox Code Playgroud)
但是,Com和ComPercent并没有成为价值观.我如何能够检索其中的值?我检索它们的循环如下
更新
foreach (var item in result)
{
dt.Rows.Add(item.Days, item.Com, item.ComPercent);
}
Run Code Online (Sandbox Code Playgroud)
我不想在我的foreach循环上做任何处理,我想在我的linq查询本身中的值.
编译器不知道您的子查询将始终返回一行,因为返回类型仍然是IEnumerable(或IQueryable).这可以通过使用First()或Single()(或相应的..OrDefault()版本)来解决,但是,更常见的是在Count()没有分组的情况下使用,例如:
Com = (from cr1 in cumulativeresult
where cr1.Days < cr.Days
select cr1
).Count() + cr.Com,
Run Code Online (Sandbox Code Playgroud)
您可能还想考虑将子查询移动到let子句中,因此可以重用它来计算Com和ComPercent:
var result = from cr in cumulativeresult
let totalCount =
(from cr1 in cumulativeresult
where cr1.Days < cr.Days
select cr1
).Count() + cr.Com
orderby cr.Days
select new
{
Days = cr.Days,
Com = totalCount,
ComPercent = Math.Round((double)totalCount / ComCount * 100, 2)
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9097 次 |
| 最近记录: |