我需要将内存中的元组与表进行比较。我尝试了以下查询,但它不起作用,
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/