Search code examples
c#linq

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

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?


Solution

  • 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.