【问题标题】:Declare variable for ConcurrentDictionary.Select()为 ConcurrentDictionary.Select() 声明变量
【发布时间】:2014-06-24 16:30:08
【问题描述】:

我有一个简单的 ConcurrentDictionary,我正在尝试选择值的子集。

我正在使用这段代码,我可以让它工作的唯一方法是 var 来声明 testStudents。这段代码的正确声明是什么?我尝试了 List 和 IEnumrable 但它们不起作用。

            public ConcurrentDictionary<string, Student> _Student = new ConcurrentDictionary<string, Student>();

            var testStudents = this._Student.Values.Select( s => s.Name = "jack");

【问题讨论】:

  • 它看起来像一个列表?哦,通过调用 .ToList() 并检查 testStudents 来确定它。事实上,你是不是把每个学生的名字都设置为jack?
  • 我假设您打算使用Where(s =&gt; s.Name == "jack")。在这种情况下,testStudents 将是一个IEnumerable&lt;Student&gt;。您当前的表达式将每个值的名称设置为“jack”并计算为字符串。
  • IEnumerable....但是你可以不理会 var 因为编译器会推断出正确的类型。
  • Select 表示映射集合(每个元素必须通过映射函数转换为另一个元素)。 Where 表示按条件过滤收集。
  • 可能你想要var testStudents = this._Student.Values.Where( s =&gt; s.Name = "jack");

标签: c# linq dictionary


【解决方案1】:

谢谢大家。看起来我使用了错误的方法。 Where 方法是我需要使用的。

IEnumerable<Student> testStudents
     = this._Student.Values.Where( s => s.Name = "jack");

【讨论】:

    猜你喜欢
    • 2015-06-30
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    • 2013-05-28
    • 2015-09-04
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多