【问题标题】:Create list of T2 from list of T1, using T2's constructor that requires T1 [duplicate]使用需要 T1 的 T2 构造函数从 T1 列表创建 T2 列表 [重复]
【发布时间】:2020-06-29 19:16:21
【问题描述】:

如果我从方法 GetType1List 获得 Type1 的列表

List<Type1> Type1List = GetType1List();

然后我可以创建一个Type2 的列表,并使用foreach 在第一个列表中循环,以使用需要Type1 实例的构造函数添加新的Type2

List<Type2> Type2List = new List<Type2>();
foreach(Type1 type1 in Type1List)
{
    Type2List.Add(new Type2(Type1));
}

有没有什么方法可以在不创建Type1 的初始列表和foreach 循环的情况下结束它?

【问题讨论】:

    标签: c# .net list


    【解决方案1】:

    使用 LINQ Select:

    List<Type2> Type2List = Type1List
        .Select(type1 => new Type2(type1))
        .ToList();
    

    【讨论】:

      【解决方案2】:

      你可以使用 Linq:

      var TypeList2 = GetType1List().Select(type1 => new Type2(type1)).ToList();
      

      【讨论】:

        【解决方案3】:

        最简单的方法似乎是List&lt;T&gt;.ConvertAll() 方法,不使用System.Linq 参考

        var Type1List = GetType1List();
        var Type2List = Type1List.ConvertAll(t1 => new Type2(t1));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-03-10
          • 1970-01-01
          • 2018-10-25
          • 2010-12-18
          • 1970-01-01
          • 2014-08-26
          相关资源
          最近更新 更多