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,013
  • 19
  • 53
  • 98

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
  • 236,029
  • 38
  • 403
  • 530
4
var list = deals.Select(d => new DealBookmarkWrapper(d))
                .Cast<IBookmarkWrapper>()
                .ToList();
Daniel A. White
  • 181,601
  • 45
  • 354
  • 430
3

How about

 var list = deals.ConvertAll(item=>new DealBookmarkWrapper(item)); 
Justin Harvey
  • 14,176
  • 2
  • 26
  • 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,337
  • 17
  • 35