Consider this snippet of code:
public static class MatchCollectionExtensions
{
public static IEnumerable<T> AsEnumerable<T>(this MatchCollection mc)
{
return new T[mc.Count];
}
}
And this class:
public class Ingredient
{
public String Name { get; set; }
}
Is there any way to magically transform a MatchCollection object to a collection of Ingredient? The use-case would look something like this:
var matches = new Regex("([a-z])+,?").Matches("tomato,potato,carrot");
var ingredients = matches.AsEnumerable<Ingredient>();
Update
A pure LINQ based solution will suffice as well.
Only if you have some way to transform a Match to an Ingredient. Since there isn’t a generic way to do this, you’ll probably need to give your method a bit of help. For example, your method could take a
Func<Match, Ingredient>to perform the mapping:and you could then call this as follows:
You can also bypass creating your own method and just use Select, with the Cast operator to deal with the weak typing of MatchCollection: