tags:

views:

231

answers:

2

I'm still having problems to write lambda expressions that should create some object and to set properties with the object initializer.

How would this query be written as a lambda expression?

List<CategoryContainer> _catList = (from q in _dc.Category
                                   select new CategoryContainer
                                   {
                                     IDCategory = q.IDCategory,
                                   }).ToList();
+5  A: 

Like this:

dc.Category.Select(q => new CategoryContainer {
                       IDCategory = q.IDCategory,
                   }).ToList();
SLaks
Thanks, I always wondered how to this ;)
citronas
+2  A: 

Another option is ConvertAll:

dc.Category.ConvertAll<CategoryContainer>( q => new CategoryContainer { 
IDCategory = q.IDCategory, }).ToList();
ewrankin
`ConvertAll` is a method on `List<T>`. If `dc.Category` isn't a `List<T>`, `ConvertAll` will not exist. Also, `ConvertAll` already returns a `List<T>`, so there's no point in calling `ToList`.
SLaks
Very good point, I made assumptions based on the code snippet. But this is an option for apps using .NET 2 with the use of a delegate, since Linq didn't exist until later (even though the question author is clearly using Linq).
ewrankin