I have a simple object in the format of
class MyObject {
public string foo;
public string bar;
}
I have a list of these objects, where the value of ‘foo’ is unique, and the value of ‘bar’ is not. For example – Imagine the values were as follows
- Foo1, Bar1
- Foo2, Bar2
- Foo3, Bar1
- Foo4, Bar3
I’m looking to group up the items so they are as follows, a Dictionary<string,List<string> with unique ‘bar’ keys, and a List<string> of their associated ‘foo’ values.
- Bar1, [Foo1,Foo3]
- Bar2, [Foo2]
- Bar3, [Foo4]
I can do this using a fairly simple loop –
Dictionary<string,List<string>> result = new Dictionary<string,List<string>>();
myObjectList = new List<MyObject>();
foreach (MyObject obj in myObjectList)
{
if (result.ContainsKey(obj.bar))
{
result[obj.bar].Add(obj.foo);
}
else
{
result.Add(obj.bar,new List<string> {obj.foo});
}
}
But I’m trying to learn how to use LINQ correctly, and it seems like there would be an elegant solution using that. What would the correct way to do this using LINQ?
It sounds like you really just want a
Lookupvia theToLookupmethod:If you really need a
Dictionaryyou could use something like:… but I’d use a lookup if you can.