2015-10-19 122 views
-1

內字符串比較數組元素我有這樣的模式:與LINQ查詢

public class Model_Test 
    { 
     public string Prop1 { get; set; }    
     public string Prop2 { get; set; } 
     public string[] Prop3 { get; set; } 
    } 

檢查Prop3是一個數組。裏面Prop3

值也像{"answer1","answer2","answer3"}

我需要做一個查詢,只需要在Model_Test對象,其中answer3爲「是」,我triyng這樣的:

result = from q in Model_Test 
     where q.Prop3[2] == "Yes"      
     select new { Name = Prop1, Value = Prop2 }; 

當我執行此查詢我收到此錯誤:

無法識別的表達式節點:ArrayIndex

我認爲這個問題是我的查詢中的這一部分:q.Prop3[2]

我感謝你的幫助。

+0

''Model_Test''是查詢代碼塊中的一個集合嗎? –

+0

是Model_Test是一個集合 –

+1

和這個:''Name = Prop1,Value = Prop2''應該是:''Name ='q.Prop1,Value = q.Prop2'' –

回答

0

問題是表達式分析器不知道如何將數組索引操作轉換爲等效的SQL。 您可以使用任何貪婪的操作符(例如ToArray())來獲取所有數據,然後在內存中對其進行過濾。

0

你正在尋找一個基本的LINQ查詢where

// Your Model 
public class Model_Test 
    { 
     public string Prop1 { get; set; }    
     public string Prop2 { get; set; } 
     public bool[] Prop3 { get; set; } 
    } 

//Usage 
List<Model_Test> lst = new List<Model_Test>(){ 
     new Model_Test{Prop1="Foo", Prop2="Bar",Prop3 = new bool[]{true,false,true}}, 
     new Model_Test{Prop1="Foo2", Prop2="Bar2",Prop3 = new bool[]{true,false,false}}, 
     new Model_Test{Prop1="Foo3", Prop2="Bar3",Prop3 = new bool[]{true,false,true}}, 
    }; 

    // Query Expression 
    var result = from element in lst 
       where element.Prop3[2] == true 
       select new {Name = element.Prop1, Value = element.Prop2}; 

    // Lambda Expression  
    var result2 = lst.Where(x=>x.Prop3[2]==true).Select(x=> new {Name=x.Prop1, Value = x.Prop2}); 

但是你要確保有Prop3[2]是一個值或這將拋出異常。