说我有一个类或定义为这样一个结构:阵列中的阵列
public class foo
{
public int x;
public int y;
}
or
public struct bar
{
public int x;
public int y;
}
说我有一些阵列或对象的列表中,任一或foo's
bar's
阵列。现在我想创建一个数组或x和/或y的列表。是否有一种简单的方法可以在C#中执行此操作,而不需要遍历数组的每个foo
或bar
,然后将所需的成员变量添加到另一个数组中?
例如,这是我当前如何做它:
//For some List<foo> fooList
//get the x's and store them to the array List<int> xList
foreach (var fooAtom in fooList)
{
xList.Add(fooAtom.x);
}
是否有这样做的更快/更小的编码方式是什么? C#中是否有专门为此设计的构造?类与结构不同吗?谢谢。
可以使用LINQ。 'var allMyXs = fooList.Select(f => f.x)' –
@Asad谢谢,那正是我在寻找的 – Iowa15
那么LINQ解决方案很漂亮,但要注意性能。 Select不会比你当前的循环更快,并且如果fooList很大....(并且顺便说它仍然是一个循环) – Steve