c# - Linq 到 SQL : Compare In-Memory Tuple List Array with Table

标签 c# linq tuples

我需要将内存中的元组与表进行比较。我尝试了以下查询,但它不起作用,

var tuples = new List<Tuple<string, int>>()
            {
                new Tuple<string, int>("12222",1),
                new Tuple<string, int>("12222",2)
            };

var result = Context.infotable
      .Where(i => tuples.Any(t => t.Item1 == i.col1 && t.Item2 == i.col2)
      .ToList();

抛出以下异常:

Unable to create a constant value of type 'System.Tuple`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Only primitive types or enumeration types are supported in this context.

最佳答案

该错误表示 Linq to SQL 无法将使用 Tuple 类型的表达式转换为 SQL 结构。

PredicateBuilder 的帮助下,您可以尝试以不同的方式构建查询

var predicate = PredicateBuilder.False<infotable>();
foreach (var tuple in tuples)
{
   var item1 = tuple.Item1;
   var item2 = tuple.Item2;
   predicate = predicate.Or(t => t.Item1 == item1 && t.Item2 == item2);
}

var result = Context.infotable.Where(predicate).ToList();

如果元组列表大到足以导致 SQL 性能问题,我会格外注意。

关于c# - Linq 到 SQL : Compare In-Memory Tuple List Array with Table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44145371/

相关文章:

c# - 如何为我的 C# XNA 游戏制作 GUI?

c# - .rdl 报告未在 C# 中显示

c# - 将集合写入 Excel

swift - 使用变量访问元组的值

python - 我怎么知道在 Python 中使用什么数据类型?

c# - 无法从程序集 Newtonsoft.Json 加载类型 'Newtonsoft.Json.JsonConvert'

linq - 使用 LINQ 填充对象列表

c# - 具有 linq 数据上下文的存储过程返回值

c# - 获取没有名称的 MethodInfo 作为字符串

tuples - 元组类型与联合数组类型