Return list of specific property of object using linq

C#.NetLinqLinq Query-Syntax

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

You could also do it like this:

ids = stockItems.ConvertAll<Guid>(o => o.StockID);

Solution 3 - C#

How about something like this? Can this be simplified?

List<TranCode> alltrans = new List<TranCode>();

foreach (var bh in obj1.obj2WithCollection.obj2Collection)
{
    alltrans.AddRange(bh.obj3WithCollection.Select(e => e.TransactionCode).ToList());
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaxim GershkovichView Question on Stackoverflow
Solution 1 - C#Amiram KorachView Answer on Stackoverflow
Solution 2 - C#Ivan GolovićView Answer on Stackoverflow
Solution 3 - C#user2259416View Answer on Stackoverflow