我目前正在尋找一種可以將 an 轉換
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>>
uj5u.com熱心網友回復:
對于這個用例,通常會使用Lookup而不是 Dictionary:
var myLookup = myEnumerable.ToLookup(interval => interval.Id);
這將創建一個ILookup<Guid, DateTimeInterval>. Lookup 類似于 Dictionary,但它將鍵映射到一組值而不是單個值。
如果出于技術原因需要字典,可以將 Lookup 轉換為“經典”字典:
var myDictionary = myLookup.ToDictionary(x => x.Key);
uj5u.com熱心網友回復:
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
uj5u.com熱心網友回復:
var result = source
.GroupBy(x => x.Key)
.ToDictionary(
g => g.Key,
g => (IEnumerable<DateTimeInterval>)g);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358749.html
