linq在特定条件下得到多个值

本文关键字:条件下 linq | 更新日期: 2023-09-27 18:26:09

我使用此查询来获取基于某些条件的某些值中的值。。

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

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

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

有可能以上述方式或任何其他最好的方式写作吗?

linq在特定条件下得到多个值

它很慢,因为您正在进行几个查询,而您可以进行一个查询。

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

此外,如果i被限制为items:的计数,则不需要for循环

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

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

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;