[英]Getting list of values out of list of objects
I have a simple class:我有一个简单的类:
private class Category
{
public int Id { get; set; }
public string Value { get; set; }
}
an also a list of objects of this type:也是这种类型的对象列表:
List<Category> Categories;
I need to get a list of Ids that are in Categories list.我需要获取类别列表中的 ID 列表。 Is there a simpler way to do this than using for loop like this:有没有比使用这样的 for 循环更简单的方法:
List<int> list = new List<int>();
for (int i = 0; i < Categories.Count; i++)
{
list.Add(Categories[i].Id);
}
Thanks in advance.提前致谢。
This expression gives you the list you want:这个表达式给你你想要的列表:
Categories.Select(c => c.Id).ToList();
Also, don't forget还有,不要忘记
using System.Linq;
Use as follows.使用如下。
Categories.Select(c => c.Id).ToList();
|| ||
List<int> list = new List<int>();
foreach (Category item in Categories)
{
list.Add(item.Id);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.