LINQ select one field from list of DTO objects to array

后端 未结 5 619
我寻月下人不归
我寻月下人不归 2020-12-05 02:31

I have DTO class that defines order line like this:

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


        
相关标签:
5条回答
  • 2020-12-05 02:38

    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.

    0 讨论(0)
  • 2020-12-05 02:45

    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();
    
    0 讨论(0)
  • 2020-12-05 02:50

    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();
    
    0 讨论(0)
  • 2020-12-05 02:51

    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
    
    0 讨论(0)
  • 2020-12-05 02:58

    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();
    
    0 讨论(0)
提交回复
热议问题