简体   繁体   中英

Compare Array element with string inside linq query

I have this model:

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

Check that Prop3 is an array.

Values inside Prop3 are like {"answer1","answer2","answer3"}

I need to do a query that takes only the Model_Test objects where answer3 is "Yes", I'm triyng this:

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

When I execute this query I get this error:

Unrecognized expression node : ArrayIndex

I think the problem is in this part of my query: q.Prop3[2]

I appreciate your help.

The problem is that expression parser does not know how to translate the array index operation into equivalent SQL. You can use any greedy operator (ToArray() for example) to fetch all data and then filter it in memory.

You are looking for a basic linq where query:

// 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});

But you need to be sure that there will be a value at Prop3[2] or this will throw exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM