我试图围绕对象的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 回答
不确定你的问题是否有拼写错误,但你错过了
select s
部分我相信你错过了选择:
http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
试试这个
你的字典是哪种类型的
并且
CustomObject
类有一个名为field
的字符串属性,您正在搜索它 .您在OP中缺少一个选择,但这个答案适用于您的最后一段 .
如果您希望它返回默认值(参考类型为
null
),如果找不到匹配的元素,请使用FirstOrDefault
.