首页 文章

C#:LINQ查询来自字典语法错误,尽管在SO中重复使用

提问于
浏览
1

我试图围绕对象的LINQ,特别是在词典中,并且非常糟糕 .

我在SO上的几个线程中看到了这种语法:

var items = (from pair in m_taskDictionary
    from s in pair.Value
     s).Distinct().ToList();

但是当我尝试编译它时,我得到一个语法错误:在源类型为“System.Collections.Generic.Dictionary”的查询表达式的后续from子句中不允许使用类型为'OperationsPlannerData.OperationsTaskLabeledData'的表达式 . 调用“SelectMany”时类型推断失败 .

怎么了?我的Visual Studio太老了吗? (男孩不会让我感到惊讶 . )我正在使用VS 2008 .

以下是推荐此用法的其中一个主题的链接:

Dictionary Manipulation Using LINQ in C#

简而言之,这里's the problem I want to resolve: I want to find the first item in the dictionary for which a particular field in the Value object matches a given string. I have the dictionary already, keyed by integers, for one purpose in my application, so I' d只是使用那个字典 . SO中的各种线程建议使用 List<KeyValuePair<string, OperationsTaskLabeledData>> 对象 . 我可以很容易地创建该对象,但我也不知道如何搜索该结构 .

4 回答

  • 1

    不确定你的问题是否有拼写错误,但你错过了 select s 部分

    var items = (from pair in m_taskDictionary
        from s in pair.Value
        select s).Distinct().ToList();  // <-- added select here
    
  • 0

    我相信你错过了选择:

    var items = (from pair in m_taskDictionary
        from s in pair.Value
         select s).Distinct().ToList();
    

    http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b

  • 1

    试试这个

    var items = (from value in m_taskDictionary.Values 
                  where value.field == "a given string" 
                  select value).Distinct().ToList();
    

    你的字典是哪种类型的

    Dictionary<int, CustomObject> m_taskDictionary = new Dictionary<int, CustomObject>();
    

    并且 CustomObject 类有一个名为 field 的字符串属性,您正在搜索它 .

  • 4

    您在OP中缺少一个选择,但这个答案适用于您的最后一段 .

    m_taskDictionary.First(kvp => kvp.Value.WhateverFieldYouNeed == someString);
    

    如果您希望它返回默认值(参考类型为 null ),如果找不到匹配的元素,请使用 FirstOrDefault .

相关问题