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?
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With