In answer to the following question: How to convert MatchCollection to string array
Given The two Linq expressions:
var arr = Regex.Matches(strText,
OfType()
should be slower since doing safe type is
check before an actual explicit cast operation, in the same time Cast()
doing only explicit cast.
Theoretically OfType
woudl be faster in case of many elements with "wrong type", so loop enumerates further just after is
check, in case of Cast()
on the same collection you would end's up with an InvalidCastException
on each element of "wrong type" so this would be relatively slower.
Source code extracted using ILSpy:
// System.Linq.Enumerable
private static IEnumerable OfType(IEnumerable source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
foreach (object current in source)
{
// **Type check**
if (current is TResult)
{
// **Explicit cast**
yield return (TResult)current;
}
}
yield break;
}
// System.Linq.Enumerable
public static IEnumerable Cast(this IEnumerable source)
{
IEnumerable enumerable = source as IEnumerable;
if (enumerable != null)
{
return enumerable;
}
if (source == null)
{
throw Error.ArgumentNull("source");
}
foreach (object current in source)
{
// **Explicit cast only**
yield return (TResult)current;
}
yield break;
}