开发者

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

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 iter开发者_运维百科ation.

Does C# have capacity for this kind of operation?


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


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.


No, because PHP arrays have nothing (!) in common with C# arrays. PHP arrays are hash tables, more like C#'s System.Collections.Hashtable or System.Collections.Generic.Dictionary<k, v>. Just realized this doesn't apply here, but it's important nonetheless.

Assuming I'm reading your pseudocode correctly though, you can do what you want with a LINQ query:

var result = from item in collection
             select item.Empty() ? "foo" : "bar";

I don't see why you'd think something like array_map would be faster than iteration though -- there's going to be iteration going on somewhere, no matter how you look at it. In PHP there's a speed boost from using the builtin function because PHP is interpreted, while the guts of array_map are compiled; but C# is a compiled language.

EDIT: After reading the docs, it looks like

var result = from item in array
             select Callback(item);

does essentially what you're looking for. Not sure how to shoehorn the "callback" bit into a function though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜