LINQ从列表中选择一个字段的DTO对象数组 [英] LINQ select one field from list of DTO objects to array

查看:604
本文介绍了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.

这篇关于LINQ从列表中选择一个字段的DTO对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆