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
LINQ Oneliner
List TheListParameter = new List{"string1", "string2", "string3"};
var foundElements = MyDC.SomeTable.Where(a=> TheListParameter.Contains(a.SomeColumn)).Select(a=> a.SomeColumn);
Why everyone throws on the ToList()
is beside me. It all depends on if you need all the data realized or not.
Take this example.
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()
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.
A tiny pointer on ToList()
mid query.
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")
So if you can, perform your filtering before the ToList()
to limit the amount of data pulled from the DB.
Instead if ToList()
you can use other lists aswell like ToArray()