I wanted to run a LINQ query against a MatchCollection
object but found this wasn't possible as it doesn't implement ICollection<T>
, just ICollection
.
What is the best option for using LINQ with non-generic collections, both in terms of code conciseness but also performance and memory usage?
(If interested, here is the non-LINQuified code:)
MatchCollection fieldValues = Regex.Matches(fieldValue, @"(?<id>\d+);#(?<text>[^;|^$]+)");
foreach (Match m in fieldValues)
{
if (m.Groups["text"].Value.Equals(someString))
{
// Do stuff
}
}
Try to use the Cast extension method which will return an IEnumerable.
And event if you don't use the Cast method the compiler will infer the type of "query" to IEnumerable.
You can include your
someString
filter with LINQ as well.Note that the compiler translates a query like this...
...into this...
...so including both the type and
Cast<T>()
is redundant.Performance-wise,
Cast<T>()
just does an explicit type cast and yields the value, so the performance hit will be negligible. For legacy collections where you're not sure all members are of the desired type, you can useOfType<T>()
instead.