使用linq返回对象的特定属性列表

时间:2021-07-31 02:24:00

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 。如果我想检索所有StockID的列表并将其填充到IEnumerable或IList中。显然我可以做到这一点。

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.

但是有什么方法可以使用Linq来实现相同的结果吗?我认为Distinct()可能会这样做,但无法弄清楚如何达到预期的效果。

3 个解决方案

#1


83  

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

#2


2  

You could also do it like this:

你也可以这样做:

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

#3


0  

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


83  

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

#2


2  

You could also do it like this:

你也可以这样做:

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

#3


0  

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

相关文章