0

I have a Dictionary

Dictionary<string, List<MyClass>> MyDictionary = new Dictionary<string,List<MyClass>>(); 

I am using Linq to obtain a List (from value) via the key

List<MyClass> CurrentList = null; CurrentList = MyDictionary.Where(d => d.Key.Contains(strKey)).Select(x => x.Value).Cast<Dictionary<string, List<MyClass>>>(); 

The error I am getting is I can not convert the dictionary to my list.

Have I missed anything?

Thanks.

1
  • Why do you cast to a Dictionary if your result must be a List? Commented Aug 22, 2014 at 7:52

3 Answers 3

2

Try this:

As x.Value is List<MyClass>, so you need use SelectMany:

 List<MyClass> CurrentList = null; CurrentList = MyDictionary.Where(d => d.Key.Contains(strKey)) .SelectMany(x => x.Value).ToList(); 
Sign up to request clarification or add additional context in comments.

Comments

0

Try it

List<MyClass> CurrentList = null; CurrentList = MyDictionary.Where(d => d.Key.Contains(strKey)).ToList() .Where(x => x.Value); 

Comments

0

The issue is here:

.Select(x => x.Value)

x.Value is of type List<MyClass>, so you cannot cast it as a dictionary. So to fix your code, just use:

CurrentList = MyDictionary.Where(d => d.Key.Contains(strKey)).Select(x => x.Value).FirstOrDefault();

2 Comments

Thanks. Cannot implicitly convert error is now coming up.
I've changed my code, as I forgot to include FirstOrDefault() to retrieve the List (assuming you want just one item returned, if you want more than one, then the other answers given for this question, using SelectMany, should work for you).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.