C# 将Lambda与字典一起使用

C# 将Lambda与字典一起使用,c#,linq,lambda,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(

我正在尝试使用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");
如何使用LINQ在字典中查找值

谢谢,

瑞克

或者

var q1 = from obj in testDict.Values where obj == "Apple" select obj;

您的语句中有一个额外的“from 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");

需要澄清的是,之所以这样做,是因为字典作为IEnumerablesSecond表达式也应该有p。值==“Apple”,因为p将是一对。这将得到一个返回IEnumerable结果的表达式。如果你真的想要实际的对象,你必须调用Single()或First()第一个表达式也应该有p.Value==“Apple”,因为p将是一对。不是真的,他是从testDict.Values中选择的,这是一个IEnumerable。只有从testDict本身中选择,他才能获得KeyValuePairs。
var q1 = testDict.Where(p => p.Value == "Apple");
var q1 = from obj in testDict.Values
         where obj.Value == "Apple"
         select obj;    
var q2 = testDict
         .Where(p => p.Value == "Apple");