如何在var选项上进行循环

时间:2014-04-14 16:27:53

标签: c# iteration

我有这段代码

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"))
             };

DTgraphDataTable

的位置

我想在result上制作循环。怎么样?

2 个答案:

答案 0 :(得分:2)

您可以使用foreach

foreach (var item in result)
{
    //Your code here
}

for知道索引。但是你必须在LINQ的末尾添加.ToList()

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();

for (int i = 0; i < result.Count(); i++)
{
    //Your code here
    //Now you can do result[i].Something
}

答案 1 :(得分:0)

这是一个循环:

foreach (var item in result)
{
   //your logic to each item of loop
}