C#从类列表中提取字段列表 [英] C# Extract list of fields from list of class
本文介绍了C#从类列表中提取字段列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个特定类的元素列表.此类包含一个字段.
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
肯定有多种方法可以执行此操作,但是我还没有找到一个美观的解决方案.我认为linq可能会有所帮助,但我不确定效果如何.
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.
推荐答案
刚刚:
List<int> result = list.Select(e => e.i).ToList();
或
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.
这篇关于C#从类列表中提取字段列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文