Reputation: 3865
I have code that looks like this:
class A {
public string Name {get;set;}
public IList<string> Keywords {get;set;}
}
...
IList<A> a = new List<A>{
new A{Name = "a1", Keywords = new List<string>{"k1", "k2"}},
new A{Name = "a2", Keywords = new List<string>{"k1", "k3"}},
new A{Name = "a3", Keywords = new List<string>{"k3", "k4"}},
new A{Name = "a4", Keywords = new List<string>{"k1", "k3", "k4"}}
};
Is there any way I can use LINQ to create a dictionary in the form of:
{"k1", List<A> {a1, a2, a4}}
{"k2", List<A> {a1}}
{"k3", List<A> {a2, a3, a4}}
{"k4", List<A> {a3, a4}}
Basically mapping the objects to the keywords.
Thanks
Upvotes: 0
Views: 437
Reputation: 38179
That should do it:
var keywordsAndNames = a.SelectMany(anA => anA.Keywords.Select(kw =>
new { KeyWord = kw, Name = anA.Name }));
var lookup = keywordsAndNames.ToLookup(entry => entry.KeyWord, entry => entry.Name);
Note that this code creates a lookup and not a dictionary because for each key there are multiple names.
lookup["k1"]
returns an IEnumerable<string>
yielding "a1", "a2" and "a4" for instance.
Upvotes: 1
Reputation: 50114
Something like
var dict = a
.SelectMany(myA =>
myA.Keywords.Select(kw => new { Name = myA.Name, Keyword = kw }))
.GroupBy(pair => pair.Keyword)
.ToDictionary(g => g.Key, g => g.Select(pair => pair.Name).ToList());
should do it.
Upvotes: 1