开发者

Code clarity for converting generic list?

开发者 https://www.devze.com 2023-01-10 06:24 出处:网络
This code should convert the list of listType2s (list) to a list of type1s. I feel the functionality is somewhat difficult to ascertain though.

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>();
        l开发者_如何转开发istType2s.ForEach(t => type1s.Add((new Type1(t))));


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.


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.


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


I think the clearest way is the following

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


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

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

精彩评论

暂无评论...
验证码 换一张
取 消