5

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.

Community
  • 1
  • 1
dotnetnoob
  • 10,783
  • 20
  • 57
  • 103

4 Answers4

9

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().

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
4
var list = deals.Select(d => new DealBookmarkWrapper(d))
                .Cast<IBookmarkWrapper>()
                .ToList();
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
3

How about

 var list = deals.ConvertAll(item=>new DealBookmarkWrapper(item)); 
Justin Harvey
  • 14,446
  • 2
  • 27
  • 30
1

The question explicitly ask for 'adding a list into another list', so this one could be interesting too:

var list = new List<IBookmarkWrapper>();  //already existing
...  
deals.Aggregate(list, (s, c) => 
                      { 
                        s.Add(new DealBookmarkWrapper(c)); 
                        return s; 
                      });
Wasp
  • 3,395
  • 19
  • 37