目前,我正在寻找一种将IEnumerable<DateTimeInterval>转换为Dictionary<Guid, IEnumerable<DateTimeInterval>>的方法。
我尝试使用IEnumerable<DateTimeInterval>.ToDictionary(x => x.id),但这只是返回一个Dictionary<Guid, DateTimeInterval>,而不是想要的Dictionary<Guid, IEnumerable<DateTimeInterval>>
我做错了什么?
dateTimeInterval的定义如下:
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;
}
}在IEnumerable<DateTimeInterval>中,可能存在具有相同密钥的DateTimeIntervals。
因此,我非常希望IEnumerable.ToDictionary(x => x.key,v => v)返回,但这只是返回Dictionary<Guid, DateTimeInterval>,而不是被通缉的Dictionary<Guid, IEnumerable<DateTimeInterval>>。
发布于 2021-11-17 14:53:22
对于这个用例,人们通常使用查找而不是字典:
var myLookup = myEnumerable.ToLookup(interval => interval.Id);这将创建一个ILookup<Guid, DateTimeInterval>。查找类似于字典,但它将键映射到值集合,而不是单个值。
如果出于技术原因需要字典,可以将查找转换为“经典”字典:
var myDictionary = myLookup.ToDictionary(x => x.Key);发布于 2021-11-17 14:58:22
Dictionary<Guid, IEnumerable<DatetimeInterval>> target = source
.ToLookup(di => di.key, di => di)
.ToDictionary(@group => @group.Key, @group => @group.Select(item => item));ToLookup根据指定的属性对项进行分组ToDictionary将ILookup实现转换为DictionarySelect帮助将IGrouping转换为IEnumerable发布于 2021-11-17 14:54:18
var result = source
.GroupBy(x => x.Key)
.ToDictionary(
g => g.Key,
g => (IEnumerable<DateTimeInterval>)g);https://stackoverflow.com/questions/70006418
复制相似问题