74

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.

3 Answers 3

164
var list = stockItems.Select(item => item.StockID).ToList();
Sign up to request clarification or add additional context in comments.

3 Comments

Lol, well now I feel like an idiot. I should have worked that out. Thank you!
How can I do the inverse process?
@Pedro77 using .Reverse()?
3

You could also do it like this:

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

Comments

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());
}

1 Comment

Try use the SelectMany() function like this obj1.obj2WithCollection.obj2Collection.SelectMany(bh => bh.obj3WithCollection.Select(e => e.TransactionCode)); See stackoverflow.com/questions/1191054/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.