【问题标题】:Convert an IEnumerable<Ienumerable<T>> to Dictionary<key,IEnumerable<T>>将 IEnumerable<Ienumerable<T>> 转换为 Dictionary<key,IEnumerable<T>>
【发布时间】:2021-11-17 14:41:29
【问题描述】:

我目前正在寻找一种可以转换 IEnumerable&lt;DateTimeInterval&gt;Dictionary&lt;Guid, IEnumerable&lt;DateTimeInterval&gt;&gt;

我尝试使用IEnumerable&lt;DateTimeInterval&gt;.ToDictionary(x =&gt; x.id) 但这只是返回一个Dictionary&lt;Guid, DateTimeInterval&gt; 而不是想要的Dictionary&lt;Guid, IEnumerable&lt;DateTimeInterval&gt;&gt;

我做错了什么?

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&lt;DateTimeInterval&gt; 中可能存在具有相同键的 DateTimeIntervals。

因此我非常希望拥有 IEnumerable.ToDictionary(x => x.key, v => v) 返回 但这只是返回一个Dictionary&lt;Guid, DateTimeInterval&gt; 而不是想要的Dictionary&lt;Guid, IEnumerable&lt;DateTimeInterval&gt;&gt;

【问题讨论】:

  • stuff.ToDictionary(k =&gt; new Guid(...), v =&gt; v) ?
  • @aybe DatetimeInterval 本身有一个id,其中一些是相同的,因此应该存储在列表中
  • 向您的问题添加更多代码,因为不清楚。
  • @aybe 添加了更多代码.. 不确定这里有什么不确定..
  • 您是否在寻找ToLookup 而不是ToDictionary?字典是 1:1 键:值,而听起来您正在寻找 1:许多键:值,因为 DateTimeInterval 可以有重复的 ID

标签: c# linq dictionary


【解决方案1】:

对于这个用例,通常会使用Lookup 而不是字典:

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

这将创建一个ILookup&lt;Guid, DateTimeInterval&gt;。查找类似于字典,但它将键映射到值的集合,而不是单个值。


如果您出于技术原因需要字典,您可以将 Lookup 转换为“经典”字典:

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

【讨论】:

  • 如果这会创建一个 Lookup&lt;Guid, DateTimeInterval&gt; ,那么我如何能够检索具有特定 entity_id 的 DateTimeInterval 列表??
  • @IamnotFat:使用myLookup[myEntityId],这将是return an IEnumerable&lt;DateTimeInterval&gt;。通常,ILookup&lt;K, V&gt; 的索引器将返回 IEnumerable&lt;V&gt;(与字典相反,它只会返回 V)。
【解决方案2】:
Dictionary<Guid, IEnumerable<DatetimeInterval>> target = source
    .ToLookup(di => di.key, di => di)
    .ToDictionary(@group => @group.Key, @group => @group.Select(item => item));
  • ToLookup 根据指定属性对项目进行分组
  • ToDictionaryILookup 实现转换为 Dictionary
  • Select 有助于将 IGrouping 转换为 IEnumerable

【讨论】:

    【解决方案3】:
    var result = source
      .GroupBy(x => x.Key)
      .ToDictionary(
        g => g.Key,
        g => (IEnumerable<DateTimeInterval>)g);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-24
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 2012-09-17
      • 1970-01-01
      • 2021-12-02
      相关资源
      最近更新 更多