2014-07-08 32 views
2

说我有一个类或定义为这样一个结构:阵列中的阵列

public class foo 
{ 
    public int x; 
    public int y; 
} 

or 

public struct bar 
{ 
    public int x; 
    public int y; 
} 

说我有一些阵列或对象的列表中,任一或foo'sbar's阵列。现在我想创建一个数组或x和/或y的列表。是否有一种简单的方法可以在C#中执行此操作,而不需要遍历数组的每个foobar,然后将所需的成员变量添加到另一个数组中?

例如,这是我当前如何做它:

//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#中是否有专门为此设计的构造?类与结构不同吗?谢谢。

+2

可以使用LINQ。 'var allMyXs = fooList.Select(f => f.x)' –

+0

@Asad谢谢,那正是我在寻找的 – Iowa15

+0

那么LINQ解决方案很漂亮,但要注意性能。 Select不会比你当前的循环更快,并且如果fooList很大....(并且顺便说它仍然是一个循环) – Steve

回答

3

你可以使用LINQ查询:

Int32[] xArray = fooList.Select(fooItem => fooItem.x).ToArray(); 

这LINQ查询工作会以同样的方式对类和结构两者。但是在某些情况下,结构值可能是boxed,它们将会多次为copied(它们是结尾的结构 - 按值传递) - 所有这些都会导致对其进行多个LINQ操作的大型结构的可能开销。

还要考虑到LINQ不是every possible situation的工具。有时,简单的forwhile)循环将更具可读性并且会提供更高的性能。

+0

感谢这是我正在寻找! – Iowa15

+0

阅读http://stackoverflow.com/questions/11344019/linq-and-lambda-expression和http://msdn.microsoft.com/en-us/library/bb397687.aspx。简而言之:列表中的每个项目都将被表示为'fooItem',并且从这个'fooItem'中的每个项目都将采用'.x'字段,并且所有这些x字段将统一在一个数组中。 –

+2

这根本不涉及拳击。它*复制*他们,这是完全不同的。 (还有OP特别表示他不想做的事情。) – Servy

1

如果他们有共同的东西,你也可以创建一个itnerface

public interface IFooBarable 
{ 
    int x; 
    int y; 
} 

,然后您的收藏也只是一个List<IFooBarable>中,你可以把你既FooBar对象,他们可以访问同样的方式。

1

我会做一个基类或具有x和y属性的接口。这样可以让更多的灵活性,在遍历集合:

public interface IHasXY { int x { get; } int y { get; } } 

public class Foo : IHasXY { public int x { get; set; } public int y { get; set; } } 
public struct Bar : IHasXY { public int x { get; set; } public int y { get; set; } } 

话,甚至可以CONCAT foo和酒吧集合:

var allXs = fooList.Concat(barList).Select(o => o.x).ToArray();