Search code examples
c#linqsorteddictionary

Use LINQ to search items in a SortedDictionary


I have a SortedDictionary of the type:

SortedDictionary<PriorityType, List<T>> dictionary;

where PriorityType is an Enum class, and the List contains various string values.

I want to use LINQ to search for the string items in the list, that have an even length. As in:

IEnumerable<T> filteredList = new List<T>();  

// Stores items in list whose string length is even
filteredList = //LINQ code;

I have tried a lot of implementations of LINQ but, it seems tough to traverse a List in a SortedDictionary using LINQ (taking into account I'm relatively new to LINQ).

Please help me with the LINQ code. Thanks!


Solution

  • If I understand you correctly, then you need items from lists which have even count of items:

    filteredList = dictionary.Select(kvp => kvp.Value)
                             .Where(l => l != null && l.Count % 2 == 0)
                             .SelectMany(l => l)
                             .ToList();
    

    UPDATE: If you want to select strings with even length, then you should use List<string> instead of generic list of T:

    SortedDictionary<PriorityType, List<string>> dictionary;
    filteredList = dictionary.SelectMany(kvp => kvp.Value)
                             .Where(s => s.ToString().Length % 2 == 0)
                             .ToList();