使用LINQ和C#从旧列表创建新列表 [英] Use LINQ and C# to make a new List from an old List
本文介绍了使用LINQ和C#从旧列表创建新列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这应该很简单,但是我是LINQ的新手.我有一个List<FillStruct>
的FillList
结构.我想使用LINQ创建一个新的List<NewFillStruct>
,在这里我没有一个包含购买和出售数量的变量,而是一个包含总和的变量.
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.
例如,如果FillStruct
结构具有
buy = 4
和
sell = 2
然后NewFillStruct
结构将具有
numlong = 2.
如果FillStruct
结构具有
buy = 2
和
sell = 4
然后NewFillStruct
结构将具有
numlong = -2.
这里是结构.
struct FillStruct
{
int buy;
int sell;
string date;
}
struct NewFillStruct
{
int numlong;
string date;
}
推荐答案
List<FillStruct> origList = ...
List<NewFillStruct> newList = origList.Select(x => new NewFillStruct {
numlong = x.buy - x.sell, date = x.date
}).ToList();
但是,请注意,struct
不一定是 的最佳选择(除非您有充分的理由,否则最好选择class
).
However, note that struct
is not necessarily a good choice for this (prefer class
unless you have a good reason).
或者完全避免使用LINQ:
Or to avoid LINQ entirely:
List<NewFillStruct> newList = origList.ConvertAll(x => new NewFillStruct {
numlong = x.buy - x.sell, date = x.date
});
这篇关于使用LINQ和C#从旧列表创建新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文