c# - Add objects to a List nested inside a Dictionary using LINQ extensions -
i have dictionary<t, t> contains key (that represents category) empty list<t> value:
dictionary<string, list<imyobject>> myobjects; each pair looks this:
{ firstcategory, new list<imyobject>> } i have list<t> of imyobject's:
list<imyobject> myobjectsunsorted; i want loop through myobjectsunsorted , add correct list<t>
foreach (var myobject in myobjectsunsorted) { myobjects[myobject.category].add(myobject); } how can without loop? example linq extension method? other objects in example created .select() dosen't fit bill in last foreach.
i suggest using lookup instead:
ilookup<string, imyobject> lookup = myobjectsunsorted.tolookup(t => t.category); ilookup<,> precisely designed "multiple values per key" dictionary. being incredibly simple construct, has benefit if key isn't represented, empty sequence instead of exception. can always write:
foreach (var item in lookup[key]) { ... } as opposed to:
ilist<myobject> list; if (dictionary.trygetvalue(key, out list)) { foreach (var item in list) { ... } } note lookup immutable in can't change items in after construction. (if items mutable reference types, can modify objects of course...) can blessing or curse, depending on situation...
Comments
Post a Comment