Linq List<> problem
NorthwindDataContext db = new No开发者_Python百科rthwindDataContext();
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.
Your query is selecting an anonymous type, not instances of Category
. That's why you're going to need to either:
- Use var instead of
List<>
- Create a named type instead of using an anonymous type in your query.
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...
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.
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();
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();
精彩评论