Tutorial :Code clarity for converting generic list?



Question:

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))));  


Solution:1

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.


Solution:2

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.


Solution:3

var type1s = listType2s.Select(o => new Type1(o)).ToList();  


Solution:4

I think the clearest way is the following

var type1s = listType2s.Select(x => new Type1(x)).ToList();  


Solution:5

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

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »