【问题标题】:Select a Dictionary<T1, T2> with LINQ使用 LINQ 选择 Dictionary<T1, T2>
【发布时间】:2009-03-06 00:20:24
【问题描述】:

我使用“select”关键字和扩展方法通过 LINQ 返回 IEnumerable&lt;T&gt;,但我需要返回通用 Dictionary&lt;T1, T2&gt; 并且无法弄清楚。我从中学到的示例使用了类似于以下形式的内容:

IEnumerable<T> coll = from x in y 
    select new SomeClass{ prop1 = value1, prop2 = value2 };

我也对扩展方法做了同样的事情。我假设由于Dictionary&lt;T1, T2&gt; 中的项目可以迭代为KeyValuePair&lt;T1, T2&gt;,我可以将上面示例中的“SomeClass”替换为“new KeyValuePair&lt;T1, T2&gt; { ...”,但这不起作用(键和值被标记为只读的,所以我无法编译这段代码)。

这可能吗,还是我需要分多个步骤执行此操作?

谢谢。

【问题讨论】:

    标签: c# .net linq generics


    【解决方案1】:

    扩展方法还提供ToDictionary 扩展。使用起来相当简单,一般的用法是为键传递一个 lambda 选择器并将对象作为值,但是您可以为键和值都传递一个 lambda 选择器。

    class SomeObject
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
    
    SomeObject[] objects = new SomeObject[]
    {
        new SomeObject { ID = 1, Name = "Hello" },
        new SomeObject { ID = 2, Name = "World" }
    };
    
    Dictionary<int, string> objectDictionary = objects.ToDictionary(o => o.ID, o => o.Name);
    

    那么objectDictionary[1] 将包含值“Hello”

    【讨论】:

      【解决方案2】:

      更明确的选择是将集合投影到 KeyValuePair 的 IEnumerable,然后将其转换为字典。

      Dictionary<int, string> dictionary = objects
          .Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
          .ToDictionary(x=>x.Key, x=>x.Value);
      

      【讨论】:

      • 是否可以删除 .ToDictionary(x=>x.Key, x=>x.Value);并用新的字典替换新的 KeyValuePair ?
      【解决方案3】:
      var dictionary = (from x in y 
                        select new SomeClass
                        {
                            prop1 = value1,
                            prop2 = value2
                        }
                        ).ToDictionary(item => item.prop1);
      

      假设SomeClass.prop1 是字典所需的Key

      【讨论】:

      • .ToDictionary(item =&gt; item.prop1, item =&gt; item.prop2); 也明确设置值。
      猜你喜欢
      • 2010-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-03
      • 2018-10-25
      • 2011-11-05
      • 1970-01-01
      • 2014-08-26
      相关资源
      最近更新 更多