Return list of specific property of object using linq

74,310

Solution 1

var list = stockItems.Select(item => item.StockID).ToList();

Solution 2

You could also do it like this:

ids = stockItems.ConvertAll<Guid>(o => o.StockID);
Share:
74,310
Maxim Gershkovich
Author by

Maxim Gershkovich

Developer with experience in. ASP.NET Azure Point of sale software C# VB.NET .NET Framework Sharepoint MVC Microsoft Kinect for Windows 1.8 &amp; 2

Updated on July 08, 2022

Comments

  • Maxim Gershkovich
    Maxim Gershkovich almost 2 years

    Given a class like this:

    public class Stock
    {
        public Stock() {}
        public Guid StockID { get; set; }
        public string Description { get; set; }
    }
    

    Lets say I now have a List<Stock>. If I would like to retrieve a list of all the StockIDs and populate it into a IEnumerable or IList. Obviously I can do this.

    List<Stock> stockItems = new List<Stock>();
    List<Guid> ids = new List<Guid>();
    
    foreach (Stock itm in stockItems) 
    {
        ids.Add(itm.StockID);
    }
    

    But is there some way I could use Linq to achieve the same result? I thought Distinct() might do it but couldn't work out how to achieve the desired result.