drouning
drouning

Reputation: 385

How to use LINQ to reduce a <string,list<string>> to <string,string>?

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?

Upvotes: 3

Views: 191

Answers (1)

ocuenca
ocuenca

Reputation: 39386

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

Upvotes: 7

Related Questions