Create a list from another list

前端 未结 4 1400
北海茫月
北海茫月 2021-01-04 05:23

Let\'s say I have:

class Plus5 {
    Plus5(int i) {
         i+5;
     }
}
List initialList = [0,1,2,3]

How I can create, from <

相关标签:
4条回答
  • 2021-01-04 05:59

    Use LINQ to add 5 to each number in your list.

    var result = initialList.Select(x => x + 5);
    
    0 讨论(0)
  • 2021-01-04 06:02
    List<Plus5> result = new List<Plus5>(InitialList.Select(x=>new Plus5(x)).ToList()));
    
    0 讨论(0)
  • 2021-01-04 06:04

    How i can create, from initialList, another list calling Plus5() constructor for each element of initialList?

    So the result is List<Plus5> newList and you want to create a new Plus5 for every int in initialList:

    List<Plus5> newList = initialList.Select(i => new Plus5(i)).ToList();
    

    If you want to micro-optimize(save memory):

    List<Plus5> newList = new List<Plus5>(initialList.Count);
    newList.AddRange(initialList.Select(i => new Plus5(i)));
    
    0 讨论(0)
  • 2021-01-04 06:22

    You can use LINQ as roughnex mentioned.

    var result = initialList.Select(x => x + 5).ToList();
    

    If you had a method (like Plus5), it would look like so

    int Plus5(int i)
    {
        return I + 5;
    }
    
    var result = initialList.Select(Plus5).ToList();
    
    0 讨论(0)
提交回复
热议问题