c# - LINQ generic function for find in a enumerable -


i need create method generic enumerable of type t finds inside using in term specify

public static object findinlist<t>(t[] list, string searchterm, string seachindex) {     string normalized1 = regex.replace(seachindex, @"\s", "");     var sel = (from l in list                      normalized1.equals([the item want compare])                      select l).firstordefault();     return sel ; } 

i need because want create generic method search item in array can customize in way (below code in original way)

[...] string normalized1 = regex.replace(seachindex, @"\s", ""); sel = (from l in list         normalized1.equals(l.ordine)         select l).firstordefault(); [...] 

[edit] servy answer. full index of answer add here how call method

func<xxx, string> keyselector = delegate(xxx b) { return b.xx; }; var return = findinlist<xxx>(list, keyselector, seachindex); 

where xxx type of list , xx property want compare search

what need here method accept selector, function determines should compare each of objects.

public static t findinlist<t>(     ienumerable<t> sequence,     func<t, string> keyselector,     string searchterm,     string seachindex) {     string normalized1 = regex.replace(seachindex, @"\s", "");     return (from l in sequence             normalized1.equals(keyselector(l))             select l).firstordefault(); } 

you can return t instead of object, since know that's is, ensuring caller doesn't need cast is. can accept ienumerable instead of array since you're ever iterating it, giving caller more flexibility while still letting need do.


Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -