Does C # have a ContainsAny () method for a dictionary?

I have a dictionary where the key is Id and the value is a string

Now I have a list of objects where each person has the CarIds property, which is

IEnumerable<int>

I want to basically filter the list of objects to include only those objects where one of the properties is included in the dict.

For instance. something like that:

var dictionary = GetDict();

var people = GetPeople();

 people = people.Where(r => dictionary.ContainsAny(r.CarIds)).ToList();

Is there something like this where I can do something similar to ContainsKey () but check something in the ints list?

+5
source share
2 answers

Yes, you can try this for lists:

people = people.Where(r => list.Intersect(r.CarIds).Count() != 0).ToList();

For dictionaries, you can use this:

people = people.Where(r => r.CarIds.Any(n => dictionary.ContainsKey(n))).ToList();
+5
source

your best bet is probably to expand the dictionary (which probably should have ContainsAny()or ContainsAnyKey()).

 public static bool ContainsAny<K, V>(
        this Dictionary<K, V> dict, IEnumerable<K> keys)
 {
     foreach(K key in keys)
         if(dict.ContainsKey(key)) return true;
     return false;
 }

and it could be linq'd like:

    public static bool ContainsAny<K, V>(
           this Dictionary<K, V> dict, IEnumerable<K> keys)
    {  return keys.Any(key => dict.ContainsKey(key));  }
+6
source

All Articles