Return list of specific property of object using linq

两盒软妹~` 提交于 2019-11-29 00:18:14

问题


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.


回答1:


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



回答2:


You could also do it like this:

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



回答3:


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


来源:https://stackoverflow.com/questions/11574376/return-list-of-specific-property-of-object-using-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!