2015-10-19 83 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]是一个值或这将抛出异常。