Snowy
Snowy

Reputation: 6122

Linq Convert to Custom Dictionary?

.NET 4, I have

public class Humi
{
public int huKey { get; set; }
public string huVal { get; set; }
}

And in another class is this code in a method:

IEnumerable<Humi> someHumi = new List<Humi>(); //This is actually ISingleResult that comes from a LinqToSql-fronted sproc but I don't think is relevant for my question
var humia = new Humi { huKey = 1 , huVal = "a"};
var humib = new Humi { huKey = 1 , huVal = "b" };
var humic = new Humi { huKey = 2 , huVal = "c" };
var humid = new Humi { huKey = 2 , huVal = "d" };

I want to create a single IDictionary <int,string[]>

with key 1 containing ["a","b"] and key 2 containing ["c","d"]

Can anyone point out a decent way to to that conversion with Linq?

Thanks.

Upvotes: 1

Views: 899

Answers (2)

BrokenGlass
BrokenGlass

Reputation: 160852

You can use ToLookup() which allows each key to hold multiple values, exactly your scenario (note that each key would hold an IEnumerable<string> of values though not an array):

var myLookup = someHumi.ToLookup(x => x.huKey, x => x.huVal);

foreach (var item in myLookup)
{
    Console.WriteLine("{0} contains: {1}", item.Key, string.Join(",", item));
}

Output:

1 contains: a,b

2 contains: c,d

Upvotes: 2

Rex M
Rex M

Reputation: 144112

var myDict = someHumi
    .GroupBy(h => h.huKey)
    .ToDictionary(
        g => g.Key,
        g => g.ToArray())

Create an IEnumerable<IGrouping<int, Humi>> and then project that into a dictionary. Note .ToDictionary returns a Dictionary, not an IDictionary.

Upvotes: 2

Related Questions