linq联接语法错误

本文关键字:错误 语法 linq | 更新日期: 2023-09-27 18:25:46

我使用LINQ查询来获取具有特定条件的行。这是查询。

var query = from v in dt1.AsEnumerable()
      join c in dt2.AsEnumerable() on v.Field<int>("ID") equals c.Field<int>("ID")
      where v.Field<string>("col1").Equals("abcd") 
      && (c.Field<string>("col1").Equals("8776") || c.Field<string>("col1").Equals("8775"))
      select new 
          {
             ok = (from a in v where v.Field<string>("stah").Equals("1") select a).count(),
             ok1 = (from a in v where v.Field<string>("stah").Equals("2") select a).count(),
             ok2 = (from a in v where v.Field<string>("stah").Equals("3") select a).count()
          };

中存在错误

ok = (from a in v where v.Field<string>("stah").Equals("1") select a).count()

错误为

找不到源类型的查询模式的实现"system.data.DataRow"."Where"未找到

样本输入:dt1

iD      col1      stah
1       4567        1
2       8748        2
3       3487        3
4       8776        1

dt2

iD      col1
1       4754
2       4576

输出

Get count of all rows where stah=1 && dt2.col1='4754'

但我不能让它工作。正确的语法是什么?

linq联接语法错误

如果我正确理解了你,那么这就是你需要的:-

var query = dt1.AsEnumerable()
               .Where(x => x.Field<int>("stah") == 1 
                       && dt2.AsEnumerable()
                             .Any(z => z.Field<int>("Id") == x.Field<int>("Id") 
                                      && z.Field<string>("Col1") == "4754")
                     ).Count();

@HarshitShrivastava提到,我之前的查询尝试没有考虑到所有的where条件。

这个版本混合使用Linq查询和Linq Lambda:怎么样

var query = from dataRows1 in dt1.AsEnumerable().Where(r => r.Field<string>("col1").Equals("abcd"))
               join dataRows2 in dt2.AsEnumerable().Where(r => r.Field<string>("col1").Equals("8776") || r.Field<string>("col1").Equals("8775"))
                  on dataRows1.Field<int>("ID") equals dataRows2.Field<int>("ID") into b
    select new
    {
        id = dataRows1.Field<int>("ID"),
        ok = (from a in b where a.Field<string>("stah").Equals("1") select a).Count(),
        ok1 = (from a in b where a.Field<string>("stah").Equals("2") select a).Count(),
        ok2 = (from a in b where a.Field<string>("stah").Equals("3") select a).Count()
    };

注意:我在投影输出中包含了ID字段,只是为了验证结果。根据需要拆下。