LINQ从列表中选择一个字段的DTO对象数组
我有一个定义这样的订单DTO类:
I have DTO class that defines order line like this:
public class Line
{
public string Sku { get; set; }
public int Qty { get; set; }
}
类型的列表行
填充像这样:
List<Line> myLines = new List<Line>();
myLines.Add(new Line() { Sku = "ABCD1", Qty = 1 });
myLines.Add(new Line() { Sku = "ABCD2", Qty = 1 });
myLines.Add(new Line() { Sku = "ABCD3", Qty = 1 });
我要的是使用LINQ从得到的SKU的数组 myLines
列表。我怎么能去这样做呢?
What I want is to use LINQ to get an array of SKUs from the myLines
List. How can I go about doing that?
我目前做手工像这样...
I am currently doing it manually like this ...
// Get SKU List
List<string> mySKUs = new List<string>();
foreach (Line myLine in myLines)
mySKUs.Add(myLine.Sku);
string[] mySKUsArray = mySKUs.ToArray();
提前
感谢。我试图谷歌的一个解决方案,但我不知道如何字的问题...
Thanks in advance. I was trying to google for a solution, but I wasn't sure how to word the question...
P.S。有没有使用 LINQ
的方法来达到我所目前正在与的foreach
做任何益处/性能提升?
P.S. is there any benefit/performance gain in using LINQ
method to achieve what I am currently doing with foreach
?
您可以使用:
var mySKUs = myLines.Select(l => l.Sku).ToList();
的
选择
方法,在这种情况下,从进行映射的IEnumerable<线>
到的IEnumerable<串>
(SKU的),那么了ToList()
将其转换为列表<字符串方式>
The Select
method, in this case, performs a mapping from IEnumerable<Line>
to IEnumerable<string>
(the SKU), then ToList()
converts it to a List<string>
.
请注意,这需要使用System.Linq的;
是在你的cs文件的顶部
Note that this requires using System.Linq;
to be at the top of your .cs file.