Lambda expression

I'm wondering if there is a better way to do this:

I have an object - one of the properties is a dictionary. I have a comma separated set of 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 tried, but is there a shorter way to do this?

Just to explain: filterValue is a list of values ​​(like '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


source to share


3 answers


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();

      

+4


source


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;

      

0


source


Is there a reason why you aren't just asking for a dictionary object?

var result = filterValue.Where(d => d.Value.Contains(val.ToString()).ToList();

      

You now have dictionary objects that contain a filter, so you can work with them instead of going through the extra step of building a bunch of string arrays that you don't really need.

0


source







All Articles