检查是否表包含在列表值
我有一个字符串参数列表,我想编写一个返回包含存在于表中的参数列表中值的字符串列表查询。我有以下查询,但我不能让where子句:
I have a parameter list of strings and I want to write a query that returns a list of strings that contain values of the parameter list that are present in the table. I have the following query but I can't get the where clause:
List<string> TheListParameter = new List<string>{"string1", "string2", "string3"};
var TheOutput = (from t in MyDC.SomeTable
where t.SomeColumn.Contains(TheListParameter)
select t.SomeColumn).ToList();
我怎样写其中,
子句这个搜索查询?
感谢。
LINQ Oneliner
LINQ Oneliner
List<string> TheListParameter = new List<string>{"string1", "string2", "string3"};
var foundElements = MyDC.SomeTable.Where(a=> TheListParameter.Contains(a.SomeColumn)).Select(a=> a.SomeColumn);
为什么每个人都投在了ToList()
在我旁边。这一切都取决于你所需要的所有数据实现与否。
Why everyone throws on the ToList()
is beside me. It all depends on if you need all the data realized or not.
就拿这个例子。
using(dbCtx myDc = new dbCtx()){
var unrealizedList = myDc.someEntity;
var realizedList = myDc.someEntity.ToList();
var a1 = unrealizedList.First() //Works
var b1 = realizedList.First() //Works
}
var a2 = unrealizedList.First() //Fails as unrealizedList is empty (not loaded and context is gone)
var b2 = realizedList.First() //Works because the realizedList was loaded completely by the ToList()
现在,如果你有一个全局或局部(而不是使用)了Ctx,那么你可能永远都不需要了ToList()
虽然使用使用是获得对上下文的控制可以是一个问题,当你有几个背景上海誓山盟工作的一个非常干净的方式。
Now if you have a global or local (not a using) Ctx then you might never need ToList()
albeit using using
is a nice and clean way of gaining control over your context which can be a problem when you have several contexts working on eachother.
在一个小小的指针了ToList()
中期查询。
var a = myDc.someEntity.Where(a=> a.someDate.DayOfYear == 123);
// Fails as DayOfYear cannot be translated to SQL expression
在这里,你需要投影你过滤它面前,遗憾的是所有的数据资料需要加载这么做
Here you need to project the data before you filter it, and sadly all the data needs to be loaded to do so
var a = myDc.someEntity.ToList().Where(a=> a.someDate.DayOfYear == 123);
// Works as the data no longer is filtered in SQL (the SQL is "Select * from someEntity")
所以,如果可以的话,在了ToList()
来限制数据从数据库拉出量。
So if you can, perform your filtering before the ToList()
to limit the amount of data pulled from the DB.
相反,如果了ToList()
您可以使用其他列表藏汉像 ToArray的()
Instead if ToList()
you can use other lists aswell like ToArray()