69

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.

Maxim Gershkovich
  • 45,951
  • 44
  • 147
  • 243

3 Answers3

156
var list = stockItems.Select(item => item.StockID).ToList();
Amiram Korach
  • 13,056
  • 3
  • 28
  • 30
3

You could also do it like this:

ids = stockItems.ConvertAll<Guid>(o => o.StockID);
Ivan Golović
  • 8,732
  • 3
  • 25
  • 31
1

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());
}
BartekR
  • 3,827
  • 3
  • 24
  • 33
  • 1
    Try use the `SelectMany()` function like this `obj1.obj2WithCollection.obj2Collection.SelectMany(bh => bh.obj3WithCollection.Select(e => e.TransactionCode));` See https://stackoverflow.com/questions/1191054/how-to-merge-a-list-of-lists-with-same-type-of-items-to-a-single-list-of-items?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Dennis Rosenbaum Mar 30 '18 at 11:48