C# 使用linq返回对象的特定属性列表
对于这样一个类:C# 使用linq返回对象的特定属性列表,c#,.net,linq,linq-query-syntax,C#,.net,Linq,Linq Query Syntax,对于这样一个类: public class Stock { public Stock() {} public Guid StockID { get; set; } public string Description { get; set; } } 假设我现在有一个列表。如果我想检索所有StockID的列表并将其填充到IEnumerable或IList中。显然我能做到 List<Stock> stockItems = new List<Stock>
public class Stock
{
public Stock() {}
public Guid StockID { get; set; }
public string Description { get; set; }
}
假设我现在有一个列表
。如果我想检索所有StockID的列表并将其填充到IEnumerable或IList中。显然我能做到
List<Stock> stockItems = new List<Stock>();
List<Guid> ids = new List<Guid>();
foreach (Stock itm in stockItems)
{
ids.Add(itm.StockID);
}
List stockItems=new List();
列表ID=新列表();
foreach(库存项目中的库存itm)
{
ID.Add(itm.StockID);
}
但是有没有什么方法可以使用Linq达到同样的效果?我原以为
Distinct()
可以做到,但无法解决如何达到预期效果。您也可以这样做:
var list = stockItems.Select(item => item.StockID).ToList();
ids = stockItems.ConvertAll<Guid>(o => o.StockID);
ids=stockItems.ConvertAll(o=>o.StockID);
像这样的东西怎么样?这可以简化吗
List<TranCode> alltrans = new List<TranCode>();
foreach (var bh in obj1.obj2WithCollection.obj2Collection)
{
alltrans.AddRange(bh.obj3WithCollection.Select(e => e.TransactionCode).ToList());
}
List alltrans=new List();
foreach(obj1.obj2WithCollection.obj2Collection中的变量bh)
{
alltrans.AddRange(bh.obj3WithCollection.Select(e=>e.TransactionCode.ToList());
}
Lol,现在我觉得自己像个白痴。我应该解决这个问题的。非常感谢。如何执行反向过程?@Pedro77使用.Reverse()
?尝试使用如下SelectMany()
函数obj1.obj2WithCollection.obj2Collection.SelectMany(bh=>bh.obj3WithCollection.Select(e=>e.TransactionCode))代码>参见