IEnumerable <T> for IDictionary <U, IEnumerable <T>>

What is the most effective way to convert IEnumerable<T>toIDictionary<U, IEnumerable<T>>

Where U is, for example, Guid, for which information is stored in property T.

Basically, this creates a dictionary of lists, where all the elements in the source list are grouped according to the value in the property of the objects.

Example

Object Definition:

class myObject
{
    public Guid UID { get; set; }

    // other properties
}

Start with:

IEnumerable<myObject> listOfObj;

End with:

IDictionary<Guid, IEnumerable<myObject>> dictOfLists;

The result listOfObjcontains objects that have many different but sometimes overlapping values ​​for the UID property.

+3
source share
4 answers

Using LINQ:

var dict = input.GroupBy(elem => elem.Identifier)
                .ToDictionary(grouping => grouping.Key, grouping => grouping.Select(x => x));
+5
source

- , , IDictionary<U, IEnumerable<T>>, IEnumerable<T> " " IEnumerable<T>. , O (1).

( ).

+2

An ILookup<U,T> " , ", IDictionary<U, IEnumerable<T>>, . , , :

var myLookup = listOfObj.ToLookup(x => x.UID);
+2

, - :

var dictionary = list.GroupBy(i => i.Guid,
                              (guid, i) => new { Key = guid, i })
                     .ToDictionary(i => i.Key, i => i);

, Guid .

0

Source: https://habr.com/ru/post/1795318/


All Articles