I am wondering if there is a better way of accomplishing this;
I have an object - one of the property is a Dictionary. I have a set of comma separated values. I need to filter the Dictionary and get only those elements where the Dictionary value matches at least one of the values
This is what I have tried but is there is a shorter way of doing this?
Just to explain: filterValue is the list of values(E.g. "4,5')
List<string> vals = new List<string>();
vals.AddRange(filterValue.Split(new char[]{','}));
List<T> bindingEntities = entities.Where(
e => {
foreach(KeyValuePair<string, object> kvp in e.ExtraProperties)
{
if(vals.Contains(kvp.Value.ToString()))
return true;
}
return false;
}).ToList();
3 Answers 3
You can use Any function:
List<string> vals = new List<string>();
vals.AddRange(filterValue.Split(new char[] { ',' }));
var bindingEntities = entities.Where(
e => e.ExtraProperties.Any(
kvp => vals.Contains(kvp.Value.ToString()))).ToList();
5 Comments
List<string> declaration and use the string[] returned from string.Split.List<string> vals = new List<string>();
vals.AddRange(filterValue.Split(new char[]{','}));
List<T> bindingEntities = entities.Where(
e => e.ExtraProperties.Values.Any(
val => vals.Contains(val.ToString())))
.ToList();
or
List<string> vals = new List<string>();
vals.AddRange(filterValue.Split(new char[]{','}));
List<T> bindingEntities = from e in entities
from val in e.ExtraProperties.Values
where vals.Contains(val.ToString())
select e;
5 Comments
Is there a reason aren't you just querying the dictionary object?
var result = filterValue.Where(d => d.Value.Contains(val.ToString()).ToList();
Now you have the dictionary objects that contain the filter so you can work with them instead of going through the extra step of constructing a bunch of string arrays that you don't really need.
Splitinto a list and you can just do.Split(',').filterValue, it might be more worthwhile to use aHashSet<T>instead of aList<T>. In fact, arrays support theContains()method all the same, so there is no point in creating aList<T>at all either:var vals = filtervalue.Split(new char[] {','});.