C# 将 Lambda 与字典结合使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1070158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Lambda with Dictionaries
提问by rboarman
I am trying to use LINQ to retrieve some data from a dictionary.
我正在尝试使用 LINQ 从字典中检索一些数据。
var testDict = new Dictionary<int, string>();
testDict.Add(1, "Apple");
testDict.Add(2, "Cherry");
var q1 = from obj in testDict.Values.Where(p => p == "Apple");
var q2 = from obj in testDict.Where(p => p.Value == "Apple");
The above lines, q1 and q2, both result in a compiler error.
上面的 q1 和 q2 行都会导致编译器错误。
error CS0742: A query body must end with a select clause or a group clause
How do I go about using LINQ to find values in a dictionary?
如何使用 LINQ 在字典中查找值?
Thank you,
谢谢,
Rick
瑞克
采纳答案by veggerby
Either
任何一个
var q1 = from obj in testDict.Values where obj == "Apple" select obj;
or
或者
var q1 = testDict.Where(p => p.Value == "Apple");
回答by Scott Ivey
you have an extra "from obj in" in your statements that isn't needed. Either remove that or change the .Where to the linq query syntax instead of the method syntax.
您的语句中有一个不需要的额外“来自 obj in”。删除它或将 .Where 更改为 linq 查询语法而不是方法语法。
var q1 = from obj in testDict.Values
where obj.Value == "Apple"
select obj;
var q2 = testDict
.Where(p => p.Value == "Apple");