How to use arrays for comparisons using lambdas in C#
I would like to know whether there is any way to shorten a comparison in lambdas by using arrays containing the comparison elements, instead of writing the elements one by one.
In practice, I have a Dictionary<K,V>
variable named litemList already filled with data. I would like to have another Dictionary<K,V>
variable with just some of the Keys of litemList.
lfilteredItemlist = litemList.Where(m => m.Key == "Name", m.Key == "Surname")
.ToDictionary(m => m.Key, m => m.Value);
This code works perfectly 开发者_如何转开发but when I have 10 or more Keys to filter and they might change with time (or even selected by the users), this solution is not feasible. I am looking for some solution where, assuming there is an array withall the Keys to filter, I can use something like this:
filterArray = {"Name", "Surname"};
lfilteredItemlist = litemList.Where(m => m.Key == filterArray)
.ToDictionary(m => m.Key, m => m.Value);
I am quite sure that there is a method because once I saw it when looking for material about Dynamic LINQ. Unfortunately I cannot find the article again and Scott Guthrie does not mention it in his blog.
Thanks
Francesco
How about changing the code to this:
lfilteredItemlist = litemList.Where(m => filterArray.Contains(m.Key))
.ToDictionary(m => m.Key, m => m.Value);
精彩评论