Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This should be pretty simple, but I am new at LINQ. I have a List<FillStruct> of FillList structs. I'd like to use LINQ to create a new List<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 has

buy = 4 

and

sell = 2

then the NewFillStruct structure will have

numlong = 2.

If the FillStruct structure has

buy = 2 

and

sell = 4

then the NewFillStruct structure will have

numlong = -2.

Here are the structures.

struct FillStruct 
{
    int buy;
    int sell;
    string date;
}

struct NewFillStruct
{
    int numlong;
    string date;
}
like image 277
Addie Avatar asked Mar 15 '10 06:03

Addie


1 Answers

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
});
like image 172
Marc Gravell Avatar answered Nov 15 '22 14:11

Marc Gravell