Reputation: 6768
NorthwindDataContext db = new NorthwindDataContext();
List<Category> lresult = (db.Categories
.Select(p => new { p.CategoryID, p.CategoryName, p.Description })).ToList();
In above query i don't want to use the var instead of var i want to use list<> but show me error .Why error occur ,How to correct this query.
Upvotes: 0
Views: 135
Reputation: 15242
To get it to work with a List<Category>
you will need to explicitly tell it to select a category item.
Like so
List<Category> lresult = (from p in db.Categories select new Category {
CategoryID = p.CategoryId,
CategoryName = p.CategoryName,
Description = p.Description }).ToList();
Upvotes: 0
Reputation: 1887
I'm pretty sure that the reason for this is because you are selecting an anonymous type. You would have to select the category itself or create another class that will hold the data.
Option 1:
NorthwindDataContext db = new NorthwindDataContext();
List<Category> result = (from cat in db.Categories
select cat).ToList();
Option 2:
public class NewCat
{
public int CategoryId,
public string CategoryName,
public string Description
}
NorthwindDataContext db = new NorthwindDataContext();
List<NewCat> result = (from cat in db.Categories
select new NewCat()
{
CategoryId = cat.CategoryID,
CategoryName = cat.CategoryName,
Description = cat.Description
}).ToList();
Upvotes: 0
Reputation: 131676
Your query is selecting an anonymous type, not instances of Category
. That's why you're going to need to either:
List<>
Anonymous types are unspeakable - there is no type name that you can refer to them in the code. They exist to make it easier to create projections in LINQ queries without having to write an explicit type for each result.
In your case, there's no real downside to just using var
. That's why it exists. It allows you to refer to anonymous types without having to give them a name (since you can't). I would just use:
var lresult = (db.Categories.Select( ... // your query...
Upvotes: 2
Reputation: 245429
You're creating a List of objects of an anonymous type. There's no way to statically declare a List that accepts anonymous objects (other than List<object>
).
The only solution would be to specify a concrete type in your Select statement:
List<MyType> lresult = db.Categories
.Select(p => new MyType() { /* assignments here */ })
.ToList();
I'd be interested to know why you don't want to use var
though. This is actually the perfect use-case for it.
Upvotes: 1