C# 从类列表中提取字段列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/994854/
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
C# Extract list of fields from list of class
提问by mafu
I've got a list of elements of a certain class. This class contains a field.
我有某个类的元素列表。这个类包含一个字段。
class Foo {public int i;}
List<Foo> list;
I'd like to extract the field from all items in the list into a new list.
我想将列表中所有项目的字段提取到一个新列表中。
List<int> result = list.ExtractField (e => e.i); // imaginary
There are surely multiple ways to do that, but I did not find a nice-looking solution yet. I figured linq might help, but I was not sure how exactly.
肯定有多种方法可以做到这一点,但我还没有找到一个漂亮的解决方案。我认为 linq 可能会有所帮助,但我不确定具体如何。
采纳答案by Jon Skeet
Just:
只是:
List<int> result = list.Select(e => e.i).ToList();
or
或者
List<int> result = list.ConvertAll(e => e.i);
The latter is more efficient (because it knows the final size to start with), but will only work for lists and arrays rather than any arbitrary sequence.
后者效率更高(因为它知道开始时的最终大小),但仅适用于列表和数组,而不适用于任何任意序列。