3

I'm calling a method with a return type of Dictionary<string, List<string>>.

The way i'm calling it i expect the List<string> to always have just 1 string element. To simplify this i'd like to use Linq to convert the return type to Dictionary<string, string>.

I got as far as to use .ToDictionary(x => x.Key, x=> x.Value); but i'm stumped on how to get the correct values. Is a conversion like this possible with LINQ?

2
  • Can't you modify the method that returns the Dictionary so that it returns Dictionary<string, string>? Commented Jul 5, 2016 at 14:27
  • It's a method in another program which i can't easily modify. Commented Jul 5, 2016 at 14:28

1 Answer 1

7

Try with:

.ToDictionary(x => x.Key, x=> x.Value.FirstOrDefault());

The value of your dictionary is a List<string>, so you can use IEnumerable<T> extension methods. Now there is several options to get the first element. Take a look this article for more details

Sign up to request clarification or add additional context in comments.

10 Comments

It might be good to explain the difference between using FirstOrDefault vs SingleOrDefault
I'd suggest using .First instead of .FirstOrDefault. Since the OP always seems to expect one result, it would probably be better to have it throw an error if there are no results.
@BradleyUffner If they always expect one then Single should be used.
@JamieR I'd still use SingleOrDefault, just in case
@cFrozenDeath Depends on the requirements, from what OP has posted he only ever expects 1, so I would think Single would have been appropriate. But I understand, it's null vs exception.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.