Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

c# - LINQ select one field from list of DTO objects to array

I have DTO class that defines order line like this:

public class Line
{
    public string Sku { get; set; }
    public int Qty    { get; set; }
}

A list of type Line is populated like so:

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 });

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. is there any benefit/performance gain in using LINQ method to achieve what I am currently doing with foreach?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use:

var mySKUs = myLines.Select(l => l.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>.

Note that this requires using System.Linq; to be at the top of your .cs file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...