C# 从对象列表中获取值列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18909452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting list of values out of list of objects
提问by Anthony
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. Is there a simpler way to do this than using for loop like this:
我需要获取类别列表中的 ID 列表。有没有比使用这样的 for 循环更简单的方法:
List<int> list = new List<int>();
for (int i = 0; i < Categories.Count; i++)
{
list.Add(Categories[i].Id);
}
Thanks in advance.
提前致谢。
采纳答案by Display Name
This expression gives you the list you want:
这个表达式给你你想要的列表:
Categories.Select(c => c.Id).ToList();
Also, don't forget
还有,不要忘记
using System.Linq;
回答by Thilina H
Use as follows.
使用如下。
Categories.Select(c => c.Id).ToList();
||
||
List<int> list = new List<int>();
foreach (Category item in Categories)
{
list.Add(item.Id);
}