Use LINQ and C# to make a new List from an old List
43,224
Solution 1
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
});
Solution 2
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
};
Author by
Addie
Updated on July 10, 2022Comments
-
Addie almost 2 years
This should be pretty simple, but I am new at LINQ. I have a
List<FillStruct>
ofFillList
structs. I'd like to use LINQ to create a newList<NewFillStruct>
where instead of having the number of buys and sells, I would have one variable containing the sum.For example, if the
FillStruct
structure hasbuy = 4
and
sell = 2
then the
NewFillStruct
structure will havenumlong = 2.
If the
FillStruct
structure hasbuy = 2
and
sell = 4
then the
NewFillStruct
structure will havenumlong = -2.
Here are the structures.
struct FillStruct { int buy; int sell; string date; } struct NewFillStruct { int numlong; string date; }
-
Sharif Lotfi about 3 yearsGreat Answer, Thank you