2

Im trying to add a dynamic where clause to my linq code. But I am getting the following error. Other samples gives the same code but they are working fine so im not sure if i missed something.

var toBeReturn = db.estimate.ToList();
if(sname != null)
{
    toBeReturn =  toBeReturn.Where(x => x.estimate_status == sname);
}

Error:

Severity Code Description Project File Line Suppression State Error CS0266 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?)

Help please

5
  • 3
    I don't understand why people downvote basic queries, if you don't know answer or consider a question not worth to answer, ignore it, but why dissuade new people needing help. Commented May 8, 2017 at 6:30
  • 1
    I am also surprised that a perfectly valid question showing the OPs efforts, expected and actual results would get downvoted. Commented May 8, 2017 at 6:32
  • @DarinDimitrov While I didn't downvote the question, the questioner seems to have ignored the error he received. We are lucky that C# (compared to, for example templated C++) gives "clear" errors. Here the error was quite. But this clearness is wasted if a person doesn't even try to read and comprehend the message.
    – xanatos
    Commented May 8, 2017 at 7:04
  • before you Judge the OP, please keep in mind that people here ask basic question so that they can apply it to more complex problem. and if you read my reply I have been trouble shooting this error. Thats why I came here to get an outside perspective on what i missed. So really? @xanatos really? Commented May 8, 2017 at 7:09
  • 1
    While the error message might seem obvious for an experienced C# developer, that might not be the case for everyone. When you say We are lucky that C# (compared to, for example templated C++) gives "clear" errors I suppose that this is your perspective. But what do you think an experienced C++ developer might say? Commented May 8, 2017 at 7:18

1 Answer 1

6

You forgot to call .ToList() at the end in order to get a List<T> which is the type of the toBeReturn variable:

toBeReturn =  toBeReturn.Where(x => x.estimate_status == sname).ToList();

Also I would recommend you inverting your logic so that you filter the results on the SQL server if the sname variable has value. In your current implementation, you are fetching all records from the table and then filter them in-memory which is not the most efficient approach.

var toBeReturn = (sname != null) 
    ? db.estimate.Where(x => x.estimate_status == sname).ToList()
    : db.estimate.ToList();
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.