We work a lot of arrays so most of out LINQ queries end up in the suffix .ToArray()
. I want to introduce a "shadow" library of LINQ methods producing arrays directly instead of the intermediate enumerables.
static class EnumerableExtensions
{
public static R[] SelectToArray<S,R>(this S[] self, Func<S, R> func)
=> self.Select(func).ToArray();
}
Then I realized that I don't really want to distinguish between Select()
and SelectToArray()
, so I changed the name accordingly. However, I'll end up in a recurrent call never going for the original version, as I've hid that with my extension method.
The best I could come up with is to trick C# to believe that I'm still dealing with IEnumerable<S>
and not S[]
.
static class EnumerableExtensions
{
public static R[] Select<S,R>(this S[] self, Func<S, R> func)
=> self.AsEnumerable().Select(func).ToArray();
}
My bother with it is twofold. First of all, it seems fishy to convert like that taking an array, making it an enumerable and then back to array. It's code smell to me but I'm not able to determine that.
Secondly, supposing that the above is fine and may be used, how do I enable C# to understand which version I'm looking for in the following sample? (I'm a strong advocate of explicit types but knowing that it's opinionated, I'd like to be able to explain to someone not sharing my sentiment.)
IEnumerable<string> thisIsEnumerable = array.Select(a => a.Property);
string[] thisIsArray = array.Select(a => a.Property);
var whatIsThis = array.Select(a => a.Property);
I know what it will be but how do I make the var
'ed thing to assume the original type (that would be in effect if we eliminate the extension method)?