2009-07-01 75 views
7

我正在嘗試使用LINQ從字典中檢索某些數據。在字典中使用Lambda

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"); 

上述行q1和q2都會導致編譯器錯誤。

error CS0742: A query body must end with a select clause or a group clause 

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

謝謝

裏克

回答

24
「從目標文件」

要麼

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

var q1 = testDict.Where(p => p.Value == "Apple"); 
+1

只是爲了澄清,這個工作的原因是字典作爲一個IEnumerable > – 2009-07-01 16:44:35

+1

第二個表達式也應該有p.Value ==「蘋果」爲P將是一對<,>。 – Richard 2009-07-01 17:03:43

8

你有一個額外的在你的語句是不必要的。要麼將其刪除,要麼將.Where更改爲linq查詢語法,而不是方法語法。

var q1 = from obj in testDict.Values 
     where obj.Value == "Apple" 
     select obj;  
var q2 = testDict 
     .Where(p => p.Value == "Apple");