C#中的array.map()示例? [英] Example of array.map() in C#?

查看:137
本文介绍了C#中的array.map()示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下常见JavaScript构造

Consider the following common JavaScript construct

var ages = people.map(person => person.age);

给出所需的结果,这是一个年龄数组。

Giving the desired result, which is an array of ages.

相当于这在 C#?请举一个简单的例子。文档指示选择或可能 selectAll 但我找不到在线示例或任何其他可能的SO问题粘贴并工作。

What is the equivalent of this in C#? Please include a simple example. The documentation indicates select or possible selectAll but I can't find an example online or any other SO question which can be pasted in and works.

如果可能的话,举个例子来改变以下数组 {1,2,3,4} 进入以下 {'1a','2a','3a','4a'} 。对于每个元素,在末尾附加a,将其从整数转换为字符串。

If possible, give an example which turns the following array {1,2,3,4} into the following {'1a','2a','3a','4a'}. For each element, append "a" to the end, turning it from an Integer to a String.

推荐答案

这称为投影在LINQ中称为选择。这不会返回一个新数组(就像JavaScript的 .map 那样),但是 IEnumerable< T> 。您可以使用 .ToArray 将其转换为数组。

This is called projection which is called Select in LINQ. That does not return a new array (like how JavaScript's .map does), but an IEnumerable<T>. You can convert it to an array with .ToArray.

var ages = people.Select(person => person.Age).ToArray();

选择适用于所有 IEnumerable< T> 哪些阵列实现。你只需要.NET 3.5和一个使用System.Linq; 语句。

Select works with all IEnumerable<T> which arrays implement. You just need .NET 3.5 and a using System.Linq; statement.

对于你的第二个例子,使用像这个。请注意,没有正在使用的数组 - 只有序列。

For your 2nd example use something like this. Notice there are no arrays in use - only sequences.

 var items = Enumerable.Range(1, 4).Select(num => string.Format("{0}a", num));

这篇关于C#中的array.map()示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆