Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to recreate this statement without using a foreach? [duplicate]

Tags:

c#

.net

linq

Possible Duplicate:
C#: Is operator for Generic Types with inheritance

Is it possible to add a list into another list whilst changing class type from Deal to DealBookmarkWrapper without using the foreach statement?

var list = new List<IBookmarkWrapper>();
foreach (var deal in deals)
{
    list.Add(new DealBookmarkWrapper(deal));
}

Thanks.

like image 329
dotnetnoob Avatar asked Sep 17 '12 14:09

dotnetnoob


2 Answers

If you want the exact equivalent:

var list = deals.Select(d => new DealBookmarkWrapper(d))
                .Cast<IBookmarkWrapper>()
                .ToList();

But if you're just iterating over the elements and don't really need a List, you can leave off the call to GetList().

like image 155
Justin Niessner Avatar answered Sep 30 '22 14:09

Justin Niessner


var list = deals.Select(d => new DealBookmarkWrapper(d))
                .Cast<IBookmarkWrapper>()
                .ToList();
like image 33
Daniel A. White Avatar answered Sep 30 '22 14:09

Daniel A. White