Home > Mobile >  Convert an IEnumerable<Ienumerable<T>> to Dictionary<key,IEnumerable<T>>
Convert an IEnumerable<Ienumerable<T>> to Dictionary<key,IEnumerable<T>>

Time:11-18

I am currently seeking a way in which i can convert an IEnumerable<DateTimeInterval> to an Dictionary<Guid, IEnumerable<DateTimeInterval>>

I tried using the IEnumerable<DateTimeInterval>.ToDictionary(x => x.id) but this just returns an Dictionary<Guid, DateTimeInterval> and not the wanted Dictionary<Guid, IEnumerable<DateTimeInterval>>

What am I doing wrong?

A dateTimeInterval is defined as such:

public class DatetimeInterval
{

    public Guid key {get; set;}
    public DateTime From { get; set; }
    public DateTime To { get; set; }

    public DatetimeInterval(DateTime from, DateTime to, Guid key)
    {
        Key = key;
        From = from;
        To = to;
    }
}

and in the IEnumerable<DateTimeInterval> there might exist DateTimeIntervals which have the same keys.

Hence I would very much like have IEnumerable.ToDictionary(x => x.key, v => v) To return but this just returns an Dictionary<Guid, DateTimeInterval> and not the wanted Dictionary<Guid, IEnumerable<DateTimeInterval>>

CodePudding user response:

For this use case, one would usually use a Lookup instead of a Dictionary:

var myLookup = myEnumerable.ToLookup(interval => interval.Id);

This will create an ILookup<Guid, DateTimeInterval>. A Lookup is similar to a Dictionary, but it maps keys to a collection of values instead of a single value.


If you need a dictionary for technical reasons, you can convert your Lookup to a "classic" dictionary:

var myDictionary = myLookup.ToDictionary(x => x.Key);

CodePudding user response:

Dictionary<Guid, IEnumerable<DatetimeInterval>> target = source
    .ToLookup(di => di.key, di => di)
    .ToDictionary(@group => @group.Key, @group => @group.Select(item => item));
  • ToLookup groups items based on a specified property
  • ToDictionary converts the ILookup implementation to Dictionary
  • Select helps to convert the IGrouping to IEnumerable

CodePudding user response:

var result = source
  .GroupBy(x => x.Key)
  .ToDictionary(
    g => g.Key,
    g => (IEnumerable<DateTimeInterval>)g);
  • Related