Generic collection fill by var value
In my code, I need help to put result
value into oList
NorthwindDataContext db = new NorthwindDataCo开发者_Go百科ntext();
List<Category> oList = new List<Category>();
var result = from p in db.Categories
select new { CategoryID = p.CategoryID, CategoryName=p.CategoryName };
I want oList
filled by result values.
Your result doesn't have the entire object that is required in the list. So you can do the following instead.
NorthwindDataContext db = new NorthwindDataContext();
List<Category> oList = new List<Category>();
oList.AddRange(db.Categories);
If adding to list is not strictly required then you can simply convert the result set to list like so:
NorthwindDataContext db = new NorthwindDataContext();
List<Category> oList = db.Categories.ToList();
You however need to know that this is sample code. Pulling the entire table like this is not probably the best thing to do (unless you know there will be fixed no. of records in table that won't change and its safe to load them all in memory).
Currently result is a collection of an anonymous type, you want it to return you a Category instead.
NorthwindDataContext db = new NorthwindDataContext();
List<Category> oList = new List<Category>();
var result = from p in db.Categories
select new Category { CategoryID = p.CategoryID, CategoryName=p.CategoryName };
You can then add your Categories to oList -
oList.AddRange(result.ToList());
EDIT:
Ok, given that you only want to get a few fields from the database, create a new type with only those fields (if you don't need to use it outside your method, you won't have to do this, just leave it as an anonymous type) -
class CategorySml
{
public int CategoryID {get; set;}
public string CategoryName {get; set;}
}
...
NorthwindDataContext db = new NorthwindDataContext();
List<CategorySml> oList = new List<Category>();
var result = from p in db.Categories
select new CategorySml { CategoryID = p.CategoryID, CategoryName=p.CategoryName };
NorthwindDataContext db = new NorthwindDataContext();
List<Category> oList = db.Categories.ToList();
Edit:
Assuming that Category
class is your own
NorthwindDataContext db = new NorthwindDataContext();
List<Category> oList = db.Categories.Select(p => new Category { CategoryID = p.CategoryID, CategoryName=p.CategoryName }).ToList();
精彩评论