Smartssolutions

Monday, May 16, 2011

Build a dynamic filter to filter a generic IEnumerable object using C# and Func

Here is the code that lets you filter a list of objects based on their properties with a dynamic way

namespace Namespace
{
    class Program
    {
      
        static void Main(string[] args)
        {
            ElementList list = new ElementList();
            IEnumerable filtredList1 = list.Filter(x=>x.prop1==1);
            IEnumerable filtredList2 = list.Filter(x => x.prop2 == "two");
            Console.ReadLine();
        }
    }

    public class Element
    {
        public int prop1 { get; set; }
        public string prop2 { get; set; }
    }

    public class ElementList: List<Element>
    {
        public ElementList()
        {
            Add(new Element{ prop1=1,prop2="one"});
            Add(new Element { prop1 = 2, prop2 = "two" });
            Add(new Element { prop1 = 3, prop2 = "three" });
            Add(new Element { prop1 = 4, prop2 = "four" });
        }

        public IEnumerable<Element> Filter(Func<Element, bool> FilterDelegate)
        {
            foreach (var item in this)
            {
                if (FilterDelegate(item)==true)
                {
                    yield return item;
                }
            }

        }
    }
}
As you see I can set a filter on the property 1 or the property twoby the way you could use delegate instead of Func if you're using anterior versions of C# 2.0 or 1.1

No comments:

Post a Comment