linq在某些条件下获得多个值

时间:2015-12-09 03:44:30

标签: c# linq lambda

我正在使用此查询根据特定条件获取某些值的值。

for (int i = 0; i < 50; i++)
{
    DataRow dr = gridviewdt.NewRow();

    dr[0] = dt.AsEnumerable()
        .Where(l => l.Field<int?>("ID") == items[i].curing_id)
        .Select(l => l.Field<string>("description"))
        .First()
        .ToString();

    dr[1] = (from row in dt.AsEnumerable()
             where row.Field<int?>("ID") == items[i].curing_id
             select row).Count();

    dr[2] = (from row in dt.AsEnumerable()
             where row.Field<int?>("ID") == items[i].curing_id && row.Field<int?>("status") == 1
             select row).Count();

    dr[3] = (from row in dt.AsEnumerable()
             where row.Field<int?>("ID") == items[i].curing_id && row.Field<int?>("status") == 2
             select row).Count();

    dr[4] = (from row in dt.AsEnumerable()
             where row.Field<int?>("ID") == items[i].curing_id && row.Field<int?>("status") == 3
             select row).Count();

    griddt.Rows.Add(dr);
}

上述语句需要更多时间在循环中多次执行查询。数据表dt也包含数十万条记录。我希望它像是

for (int i = 0; i < num_of_curing; i++)
{
    DataRow dr = gridviewdt.NewRow();

    dr[0] = dt.AsEnumerable()
        .Where(l => l.Field<int?>("ID") == items[i].curing_id)
        .Select(l => l.Field<string>("description"))
        .First()
        .ToString();

    data = dt.AsEnumerable().Where(l => l.Field<int?>("ID") == items[i].curing_id)
                .Select(g => new
                {
                    dr[1] = g.Count(),
                    dr[2] = (g.Field<int?>("status") == 1).Count(),
                    dr[3] = (g.Field<int?>("status") == 2).Count(),
                    dr[4] = (g.Field<int?>("status") == 3).Count()

                });

     gridviewdt.Rows.Add(dr);
}

是否可以用上述方式或任何其他最佳方式书写?

2 个答案:

答案 0 :(得分:2)

这很慢,因为你正在做几个查询,而你可以做一个。

此代码仅生成一个查询并将结果存储在数组中。然后,您可以安全地使用此数据。

此外,如果for仅限于i的计数,则您不需要items循环:

foreach (var item in items)
{
    DataRow dr = griddt.NewRow();

    var data = dt
        .AsEnumerable()
        .Where(l => l.Field<int?>("ID") == item.curing_id)
        .Select(l => new {
            description = l.Field<string>("description"),
            status = l.Field<int?>("status")
        })
        .ToArray();

    dr[0] = data[0].description;
    dr[1] = data.Count();
    dr[2] = data.Count(d => d.Status == 1);
    dr[3] = data.Count(d => d.Status == 2);
    dr[4] = data.Count(d => d.Status == 3);

    griddt.Rows.Add(dr);
}

答案 1 :(得分:1)

您可以使用这样的匿名对象:

var data = (from row in dt.AsEnumerable()
            where row.Field<int?>("ID") == items[i].curing_id
            select new
            {
                dr1 =  row.Count(),
                dr2 =  (row.Field<int?>("status") == 1).Count(),
                dr3 =  (row.Field<int?>("status") == 2).Count(),
                dr4 =  (row.Field<int?>("status") == 3).Count(),
            }).FirstOrDefault();

然后填充你的datarow

dr[1] = data.dr1;
dr[2] = data.dr2;