C#/Linq: Apply a mapping function to each element in an IEnumerable?

C#Linq

C# Problem Overview


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.

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

C# Solutions


Solution 1 - C#

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());

Or in LINQ syntax:

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

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

Solution 2 - C#

You're looking for Select which can be used to transform\project the input sequence:

IEnumerable<string> strings = integers.Select(i => i.ToString());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndreas BausView Question on Stackoverflow
Solution 1 - C#George DuckettView Answer on Stackoverflow
Solution 2 - C#Tim LloydView Answer on Stackoverflow