Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#/PHP : Is there an equivalent of PHP's array_map() function in C#?

Tags:

arrays

c#

php

I've been pondering this today, and I have a nagging feeling that this is something simple to implement and I'm just way out of it today, but anyway, here it is.

Instead of performing something like

// assume that I have a populated string[] myString
for (int i = 0; i < myString.Length; i++) {
    myString[i] = myString[i].Equals(string.Empty) ? "foo" : "bar;
}

I'd like to do something like PHP's array_map(), which (I think) would perform faster than explicit iteration.

Does C# have capacity for this kind of operation?

like image 983
Richard Neil Ilagan Avatar asked Jan 22 '23 12:01

Richard Neil Ilagan


2 Answers

With an extension method:

Func<string, string> mapFun = n => n.Equals(string.Empty) ? "foo" : "bar";
Enumerable<string> newNames = names.Select(mapFun);

You can also pass Func directly:

IEnumerable<string> newNames = names.Select(n => n.Equals(string.Empty) ? "foo" : "bar");

As seen on ideone. Here are a few other functions that are more or less equivalent:

PHP                C#
-------------------------------
array_map()       .Select()
array_filter()    .Where()
array_reduce()    .Aggregate()

MSDN Reference:

Enumerable Methods

like image 198
NullUserException Avatar answered Feb 09 '23 00:02

NullUserException


Yes, just use one of the Enumerable extension methods. The equivalent of array_map() is called Select():

var result = array.Select(item => item == "" ? "foo" : "bar");

For operations like this, consider using IEnumerable<T> more than T[] (arrays), but if you already have an array, you can use it because T[] actually implements IEnumerable<T>.

As a bonus, the equivalent of array_filter() is called Where():

var nonEmpty = array.Where(item => item != "");

If you’re curious what other methods there are, there is a pretty good list with examples on MSDN.

like image 34
Timwi Avatar answered Feb 09 '23 00:02

Timwi