Search code examples
c#.netlinqdictionary

Is there a LINQ function that checks whether list of objects contains an attribute that matches a dictionary value?


I have an <int, string> dictionary and I am trying to check an IEnumerable of objects to see, whether a particular attribute is contained in the dictionary. I am aware of Contains but I can't seem to reverse it if it makes sense.

If it were just one value I'd be fine but I need the list to go through the whole dictionary for each item in the list.

Currently I am using this:

foreach (var item in model)
                {
                    if (dictionary.Values.Contains(object.Attribute))
                    {
                        list.Add(object);
                    }
                }

Thank you!


Solution

  • Take a look at the code below, and if you want to play with it use this Fiddle. This takes Jon Skeet's advice to use a HashSet.

    // your dictionary of items
    var dict = new Dictionary<int, string>();
    dict.Add(0, "Zero");
    dict.Add(2, "Two");
    dict.Add(4, "Four");
    
    // as suggested by Jon Skeet, create a HashSet to be more performant
    var hs = new HashSet<string>(dict.Values);
    
    // list of unfiltered items
    var list = new List<dynamic>()
    {
        new { Id = 0, Name = "Zeroth", PropertyYouWantToCheck = "Zero" },
        new { Id = 1, Name = "First", PropertyYouWantToCheck = "One" },
        new { Id = 2, Name = "Second", PropertyYouWantToCheck = "Two" },
        new { Id = 3, Name = "Third", PropertyYouWantToCheck = "Three" },
        new { Id = 4, Name = "Fourth", PropertyYouWantToCheck = "Four" },
    };
    
    // LINQ query to filter the list
    var filteredList = list.Where(i => hs.Contains(i.PropertyYouWantToCheck));
    
    // output the name of the filtered items
    Console.WriteLine(string.Join(", ", filteredList.Select(fl => fl.Name)));