hncl
hncl

Reputation: 2295

c# List using where statement

My application is asp.net MVC using Linq-to-Sql. I am trying to use the following to filter a view.

I have already added the filter to my SQL Server view using:

WHERE (dbo.Client.Recstatus IS NULL) OR (dbo.Client.Recstatus = 0)

It works well when I run it in SQL Server Management Studio, however I still see the entries in my application.

I tried to filter it again in my repository using:

List<vw_Client_info> searchResult = new List<vw_Client_info>().Where(c=> c.Recstatus != 1);

Recstatus is smallint

I get the following error:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?)

I would appreciate your assistance, thanks in advance.

Upvotes: 0

Views: 172

Answers (4)

Damith
Damith

Reputation: 63065

two problems

  1. new List<vw_Client_info>() is new list there is no data
  2. you have to call .ToList() at the end of the statement

You can try something like below

using (YourDatacontext context= new YourDatacontext(connStr))
{
    List<vw_Client_info> searchResult = 
          context.vw_Client_infos.Where(c=> c.Recstatus != 1).ToList();
}

Upvotes: 2

Prabhu Murthy
Prabhu Murthy

Reputation: 9261

Enumerable methods inlcuding Where do not return a List but rather they return a IEnumerable

so you could modify your code to

IEnumerable<vw_Client_info> searchResult = 
          new List<vw_Client_info>().Where(c=> c.Recstatus != 1);

Or

var searchResult = 
         new List<vw_Client_info>().Where(c=> c.Recstatus != 1);

which is same as above(compiler derives the type for you)

Or

List<vw_Client_info> searchResult = 
         new List<vw_Client_info>().Where(c=> c.Recstatus != 1).ToList();

Upvotes: 0

AKD
AKD

Reputation: 3966

This is because you are returning an anonymous type from your Select and you are trying to store it in the List<vw_Client_info>. The projections always create anonymous types. so that u shd store in IEnumerable or use ToList() at tail.

Upvotes: 0

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32481

Seems you forget to use the ToList() method at the end. Try this:

List<vw_Client_info> searchResult = 
    new List<vw_Client_info>().Where(c=> c.Recstatus != 1).ToList();

Upvotes: 2

Related Questions