[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?

This question is related to c# linq

The answer is


I think you're looking for;

  string[] skus = myLines.Select(x => x.Sku).ToArray();

However, if you're going to iterate over the sku's in subsequent code I recommend not using the ToArray() bit as it forces the queries execution prematurely and makes the applications performance worse. Instead you can just do;

  var skus = myLines.Select(x => x.Sku); // produce IEnumerable<string>

  foreach (string sku in skus) // forces execution of the query

You can select all Sku elements of your myLines list and then convert the result to an array.

string[] mySKUsArray = myLines.Select(x=>x.Sku).ToArray();

In the case you're interested in extremely minor, almost immeasurable performance increases, add a constructor to your Line class, giving you such:

public class Line
{
    public Line(string sku, int qty)
    {
        this.Sku = sku;
        this.Qty = qty;
    }

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

Then create a specialized collection class based on List<Line> with one new method, Add:

public class LineList : List<Line>
{
    public void Add(string sku, int qty)
    {
        this.Add(new Line(sku, qty));
    }
}

Then the code which populates your list gets a bit less verbose by using a collection initializer:

LineList myLines = new LineList
{
    { "ABCD1", 1 },
    { "ABCD2", 1 },
    { "ABCD3", 1 }
};

And, of course, as the other answers state, it's trivial to extract the SKUs into a string array with LINQ:

string[] mySKUsArray = myLines.Select(myLine => myLine.Sku).ToArray();

This is very simple in LinQ... You can use the select statement to get an Enumerable of properties of the objects.

var mySkus = myLines.Select(x => x.Sku);

Or if you want it as an Array just do...

var mySkus = myLines.Select(x => x.Sku).ToArray();