Use LINQ and C# to make a new List from an old List

前端 未结 2 784
野性不改
野性不改 2020-12-16 16:45

This should be pretty simple, but I am new at LINQ. I have a List of FillList structs. I\'d like to use LINQ to create a new

相关标签:
2条回答
  • 2020-12-16 17:22

    This will select all your data from the enumerable "fillstructs" and create an enumerable of "NewFillStruct" containing the calculated values.

     var newfills = from fillstruct in fillstructs
                   select new NewFillStruct
                   {
                       numlong = fillstruct.buy - fillstruct.sell,
                       date = fillstruct.date
                   };
    
    0 讨论(0)
  • 2020-12-16 17:24
    List<FillStruct> origList = ...
    List<NewFillStruct> newList = origList.Select(x => new NewFillStruct {
        numlong = x.buy - x.sell, date = x.date
    }).ToList();
    

    However, note that struct is not necessarily a good choice for this (prefer class unless you have a good reason).

    Or to avoid LINQ entirely:

    List<NewFillStruct> newList = origList.ConvertAll(x => new NewFillStruct {
        numlong = x.buy - x.sell, date = x.date
    });
    
    0 讨论(0)
提交回复
热议问题