I personally use an extension method that's a little different from what others have posted so far. It specifically uses a custom WeakConverter<TSource, TResult>
delegate to avoid the issue in Ron's answer of calling ToString()
on every object, while maintaining genericity unlike Jared's answer (though I will concede that sometimes trying to make everything generic is overdoing it -- but in this case, the added effort is really not much for what I consider a significant benefit in terms of reusability).
public delegate bool WeakConverter<TSource, TResult>(TSource source, out TResult result);
public static IEnumerable<TResult> TryConvertAll<TSource, TResult>(this IEnumerable<TSource> source, WeakConverter<TSource, TResult> converter)
{
foreach (TSource original in source)
{
TResult converted;
if (converter(original, out converted))
{
yield return converted;
}
}
}
With this in place, you can convert a string[]
to an int[]
quite simply and robustly (no double-parsing necessary):
string[] strings = new[] { "1", "2", "abc", "3", "", "123" };
int[] ints = strings.TryConvertAll<string, int>(int.TryParse).ToArray();
foreach (int x in ints)
{
Console.WriteLine(x);
}
Output:
1
2
3
123