C#/ LINQ的:在一个IEnumerable应用映射函数的每个元素? [英] C#/Linq: Apply a mapping function to each element in an IEnumerable?

查看:179
本文介绍了C#/ LINQ的:在一个IEnumerable应用映射函数的每个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种方式来IEnumerable的每个元素转换成其它东西使用映射功能(在一个LINQ兼容的方式),但我没有发现任何东西。

I've been looking for a way to transform each element of an IEnumerable into something else using a mapping function (in a Linq-compatible way) but I haven't found anything.

对于一个(简单)的例子,它应该能够做到像

For a (very simple) example, it should be able to do something like

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<string> strings = integers.Transform(i => i.ToString());



但我没有发现任何东西。我的意思是,这是非常简单的编写完成了一个扩展方法(基本上,所有它需要被包装源枚举到一个新的类,然后写一点样板代码委派的调用),但我本来期望这是一个相当基本的操作,写我自己感觉就像重新发明轮子 - 我不能动摇的感觉,有可能是我应该使用一个内置的方式,我一直没盲目看吧。

But I haven't found anything. I mean, it's pretty straightforward to write an extension method that accomplishes that (basically, all it requires is wrapping the source enumerator into a new class and then writing a bit of boilerplate code for delegating the calls to it), but I would have expected this to be a fairly elementary operation, and writing it myself feels like reinventing the wheel - I can't shake the feeling that there may be a built-in way which I should be using, and I've just been too blind to see it.

所以......是有什么在LINQ的,让我做什么上述我?

So... is there something in Linq that allows me to do what I described above?

推荐答案

您可以只使用 选择( ) 扩展方法:

You can just use the Select() extension method:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<string> strings = integers.Select(i => i.ToString());

或在LINQ语法:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };

var strings = from i in integers
              select i.ToString();

这篇关于C#/ LINQ的:在一个IEnumerable应用映射函数的每个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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