views:

76

answers:

5

This code should convert the list of listType2s (list) to a list of type1s. I feel the functionality is somewhat difficult to ascertain though.

I am looking to see alternative methods that are easier to read, yet concise, and brief.

        List<Type1> type1s = new List<Type1>();
        listType2s.ForEach(t => type1s.Add((new Type1(t))));
+4  A: 

I personally like:

var type1s = (from item in listType2s select new Type1(item)).ToList();

I should say, I actually prefer

var qry = from item in listType2s 
          select new Type1(item);
var type1s = qry.ToList();

But mostly because that lets me reuse qry for other nefarious purposes if I want to.

Randolpho
+1: Bugger! You type faster than me.
kbrimington
@Randiolpho I think this code shows the intent the clearest out of the linq methods but is not as clear as using the built-in method. Thanks again!
Curtis White
+4  A: 
var type1s = listType2s.Select(o => new Type1(o)).ToList();
Kirk Woll
+3  A: 

I think the clearest way is the following

var type1s = listType2s.Select(x => new Type1(x)).ToList();
JaredPar
+1 because I also use `x`.
AMissico
+5  A: 

I generally agree with using LINQ for this sort of thing - but List<T> has had a ConvertAll method since .NET 2.0 which will actually be slightly more efficient (as it already knows the size):

List<Type1> type1s = listType2s.ConvertAll(t => new Type1(t));

I would probably use LINQ myself unless I had a particular reason not to, just because then it's consistent with the rest of the code which would probably be using LINQ too.

Jon Skeet
@Jon I think this is the clearest and most efficient.
Curtis White
A: 

If you are upcasting, this is a clear and concise idiom:

List<SubType> list1 = GetListSubType();
List<BaseType> list2 = list1.OfType<BaseType>().ToList();
David B