我试着把我的头围绕LINQ从对象,特别是在字典,和严重失败。
我在SO上的几个线程中见过这种语法:
var items = (from pair in m_taskDictionary
from s in pair.Value
s).Distinct().ToList();
但是当我尝试编译这个时,我得到一个语法错误:类型OperationsPlannerData的表达式。在源类型为'System.Collections.Generic.Dictionary'的查询表达式的后续from子句中不允许使用OperationsTaskLabeledData。调用'SelectMany'时类型推断失败。
怎么了?我的Visual Studio是不是太旧了?(我一点也不惊讶。)我用的是VS 2008。
这里有一个链接到一个建议使用这种方法的线程:
在c#中使用LINQ处理字典
简而言之,这是我想解决的问题:我想在字典中找到Value对象中特定字段与给定字符串匹配的第一项。我已经有了字典,用整数作为键值,在我的应用程序中有一个目的,所以我宁愿只使用那个字典。SO中的各种线程建议为此使用List<KeyValuePair<string, OperationsTaskLabeledData>>
对象。我可以很容易地创建那个对象,但我也不知道如何搜索那个结构
你的OP中缺少一个select,但是这个答案是针对你的最后一段的。
m_taskDictionary.First(kvp => kvp.Value.WhateverFieldYouNeed == someString);
如果您希望它在没有找到匹配元素的情况下返回默认值(引用类型为null
),则使用FirstOrDefault
。
不确定您的问题是否有打字错误,但您缺少select s
部分
var items = (from pair in m_taskDictionary
from s in pair.Value
select s).Distinct().ToList(); // <-- added select here
试试这个
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
的字符串属性,您正在进行搜索。
我想你错过了select:
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