我有一个数据表,我正在对它进行操作以获得如下结果:
var result = from row in DTgraph.AsEnumerable()
group row by row.Field<string>("Campaign") into grp
select new
{
Campaign = grp.Key,
Count = grp.Count(),
SL = grp.Sum(s => s.Field<Decimal>("Inb.ServiceLevel"))
};
我想循环播放result
我试过这两种方式:
for (int i=0;i< result.Count(); i++){
{
}
但我无法输入result[i].Count
foreach (var item in result)
{
}
答案 0 :(得分:4)
您的LINQ表达式返回IEnumerable,无法通过索引器访问。这就是您第一次尝试中result[i]
无效的原因。
修复很简单:将IEnumerable转换为List:
var result = (from ... select new { ... }).ToList();
答案 1 :(得分:0)
var result = (from row in DTgraph.AsEnumerable()
group row by row.Field<string>("Campaign") into grp
select new
{
Campaign = grp.Key,
Count = grp.Count(),
SL = grp.Sum(s => s.Field<Decimal>("Inb.ServiceLevel"))
}).ToList();
if(result.Count() > 0)
{
///Do Something////
}
答案 2 :(得分:0)
你为什么需要那个?请改用。
无论如何,如果你坚持,你可以创建一个提供这个功能的扩展功能。像这样:
public static void ForEachIndex<T>(this IEnumerable<T> collection, Action<T, int> action)
{
int index = 0;
foreach (T curr in collection)
{
action(curr, index);
index++;
}
}
用法:
List<int> collection = new List<int> {1,2,3,4,5};
int output = 0;
collection.ForEachIndex((curr,idx) => output += curr * idx);