linq 如何在C# Lambda中从键值对字典中创建where条件

r7knjye2  于 2023-01-06  发布在  C#
关注(0)|答案(1)|浏览(158)

如何从键和值对的字典中创建where条件?我有一个字典,其中包含where条件的值。

var pkkeys = new Dictionary<string, string>
{
  { "pkkey1", "value1" },
  { "pkkey2", "value2" },
  { "pkkey3", "value4" }
}

我需要创建这样的内容:

db.GetTable<SomeTable>()
  .Where(t => (t.code == "pkkey1" && t.value == "value1") 
              || (t.code == "pkkey2" && t.value == "value2")
              || (t.code == "pkkey3" && t.value == "value3"));

谢谢。
我尝试了下面的代码:

Expression<Func<SomeDictionary, bool>> e = (x) => false;

foreach (var dictKeyValue in dictKeyValues)
{
    e.Or((t) => dictKeyValue.Code == t.Code && dictKeyValue.Value == t.Value);
}

var expe = tbl => this.dbContext.Set<SomeTable>()
                      .Any(e.Compile());
dbf7pr2w

dbf7pr2w1#

表达式第一个参数类型应为SomeTable
我假设是这样的表:

public class SomeTable 
{
   public string Code { get; set;}
   
   public string Value { get; set;}

}

表情:

Expression<Func<SomeTable, bool>> e = (x) => 
                     dict.Any(a => a.Key == x.Code && a.Value == x.Value);

var result = this.dbContext.Set<SomeTable>()
                      .Where(e.Compile());

相关问题