[英]ICollection <T> to string array (using string property)
I have an ICollection
of Thing
. 我有一个
ICollection
of Thing
。 Thing
has a string
property Name
. Thing
有一个string
属性Name
。 I would like to get an array of all Name
in my ICollection
. 我想在
ICollection
获取所有Name
的数组。 I know I can do this by iterating over the collection and building the array, but is there a neater way to do this with lambda notation? 我知道我可以通过遍历集合并构建数组来实现这一点,但是有一种更简洁的方法来使用lambda表示法吗?
Sure, LINQ lets you do this very easily: 当然,LINQ可以让你轻松完成这项工作:
string[] names = things.Select(x => x.Name).ToArray();
Of course if you're just going to iterate over it, you don't need the ToArray
part: 当然,如果你只是要迭代它,你不需要
ToArray
部分:
IEnumerable<string> names = things.Select(x => x.Name);
Or you could create a List<string>
with ToList
: 或者您可以使用
ToList
创建List<string>
:
List<string> names = things.Select(x => x.Name).ToList();
In all of these cases you could use var
instead of explicitly declaring the variable type - I've only included the type here for clarity. 在所有这些情况下,您可以使用
var
而不是显式声明变量类型 - 为了清楚起见,我仅在此处包含了类型。
Using ToList
can be very slightly more efficient than using ToArray
, as the final step in ToArray
involves copying from a possibly-oversized buffer to a right-sized array. 使用
ToList
可以非常微微比使用更高效的ToArray
,因为在最后的步骤ToArray
从可能-超大缓冲至合适大小的阵列包括复制。
EDIT: Now we know you really do need an array, it would be slightly more efficient to do this yourself with a manual loop, as you know the size beforehand. 编辑:现在我们知道你真的需要一个数组,这将是稍微更高效的带手动循环来自己做,你也知道的大小提前。 I'd definitely use the first form until I knew it was a problem though :)
我肯定会使用第一种形式,直到我知道这是一个问题虽然:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.