将Lambda与词典结合使用

rbo*_*man 8 c# linq lambda

我正在尝试使用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");
Run Code Online (Sandbox Code Playgroud)

上面的行q1和q2都导致编译器错误.

error CS0742: A query body must end with a select clause or a group clause
Run Code Online (Sandbox Code Playgroud)

如何使用LINQ在字典中查找值?

谢谢,

干草堆

veg*_*rby 25

var q1 = from obj in testDict.Values where obj == "Apple" select obj;
Run Code Online (Sandbox Code Playgroud)

要么

var q1 = testDict.Where(p => p.Value == "Apple");
Run Code Online (Sandbox Code Playgroud)

  • 这些将为您提供一个返回IEnumerable结果的表达式.如果你真的想要实际的对象,你必须调用Single()或First() (5认同)

Sco*_*vey 8

你在你的陈述中有一个额外的"来自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");
Run Code Online (Sandbox Code Playgroud)

  • 不是这样,他从testDict.Values中选择,这是一个IEnumerable <string>.如果他从testDict中选择,他只会获得KeyValuePairs. (3认同)