Can this extension method be improved?

Posted by Newbie on Stack Overflow See other posts from Stack Overflow or by Newbie
Published on 2010-04-29T03:08:37Z Indexed on 2010/04/29 3:47 UTC
Read the original article Hit count: 269

Filed under:

I have the following extension method

public static class ListExtensions
    {

        public static IEnumerable<T> Search<T>(this ICollection<T> collection, string stringToSearch)
        {
            foreach (T t in collection)
            {
                Type k = t.GetType();
                PropertyInfo pi = k.GetProperty("Name");
                if (pi.GetValue(t, null).Equals(stringToSearch))
                {
                    yield return t;
                }
            }
        } 

    }

What it does is by using reflection, it finds the name property and then filteres the record from the collection based on the matching string.

This method is being called as

List<FactorClass> listFC = new List<FactorClass>();
    listFC.Add(new FactorClass { Name = "BKP", FactorValue="Book to price",IsGlobal =false  });
    listFC.Add(new FactorClass { Name = "YLD", FactorValue = "Dividend yield", IsGlobal = false });
    listFC.Add(new FactorClass { Name = "EPM", FactorValue = "emp", IsGlobal = false });
    listFC.Add(new FactorClass { Name = "SE", FactorValue = "something else", IsGlobal = false });    
   List<FactorClass> listFC1 = listFC.Search("BKP").ToList();

It is working fine.

But a closer look into the extension method will reveal that

Type k = t.GetType();
PropertyInfo pi = k.GetProperty("Name");

is actually inside a foreach loop which is actually not needed. I think we can take it outside the loop.

But how?

PLease help. (C#3.0)

© Stack Overflow or respective owner

Related posts about c#3.0