Question

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!

Was it helpful?

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

OTHER TIPS

The solution provided by @Sergey is correct & in conformance to my requirements.

Also I found another easy solution using the select statement.

filteredList = from list in dictionary.Values from item in list where item.ToString().Length % 2 == 0 select item;

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top