使用linq返回对象的特定属性的列表 [英] Return list of specific property of object using linq

查看:88
本文介绍了使用linq返回对象的特定属性的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出这样的一个类:

public class Stock
{
    public Stock() {}
    public Guid StockID { get; set; }
    public string Description { get; set; }
}

让我们说我现在有一个List<Stock>.如果我想检索所有StockID的列表并将其填充到IEnumerable或IList中.显然我可以做到这一点.

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

但是有什么方法可以使用Linq达到相同的结果吗?我以为Distinct()可以做到,但无法解决如何达到期望的结果.

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.

推荐答案

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

这篇关于使用linq返回对象的特定属性的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆