Click here to Skip to main content
15,892,575 members
Articles / Programming Languages / C#

LINQing the Reflection

Rate me:
Please Sign up or sign in to vote.
3.95/5 (11 votes)
15 Sep 2009CPOL2 min read 30K   99   12  
Using LINQ with reflection with minimum coding to access the members dynamically
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;


namespace ReflectionwithLinq
{
    static class Program
    {
        static void Main(string[] args)
        {
           // person P = new person { name = 'aa', Address = 'ba', Age = 24, City = 'cc', DOB = null, Height = 89, pincode = 89899, street = 'ss', URL = 'uu' };
            person P = new person();

            DateTime start = DateTime.Now;
            Console.WriteLine("Start Classic Load: {0}", start);

            System.Console.WriteLine("No of String Member in Classic way without linq Person Object : " + P.StringMemeberCount().ToString());
            DateTime stop = DateTime.Now;
            Console.WriteLine("Stop Classic Load: {0}", stop.Date.Millisecond);
            Console.WriteLine("Elapsed Time: {0}", stop - start);

             start = DateTime.Now;
            Console.WriteLine("Start Linq Method : {0}", start);
           
            System.Console.WriteLine("No of String Member in Person Object : " + P.StringMemeberCount().ToString());
            stop = DateTime.Now;
            Console.WriteLine("Stop Linq Method : {0}", stop);
            Console.WriteLine("Elapsed Time: {0}", stop - start);
           
            System.Console.WriteLine("No of Non-String Member in Person Object : " + P.nonStringMemeberCount().ToString());

            ///Calling Over loaded Methods  ...
            try
            {
                System.Console.WriteLine("Calling overloaded Method with one parameter : " + overloadCallClassic(P, 1));
            }
            catch (Exception e)
            {
                System.Console.WriteLine("Calling overloaded Execption : " + e.Message );
            }
            
            System.Console.WriteLine("Calling overloaded Method with one parameter : " + overloadCall(P,1));
            System.Console.WriteLine("Calling overloaded Method with 2 parameters : " + overloadCall(P,2));

            System.Console.ReadKey();

            
        }
        private static int StringMemeberCountClassic<T>(this T source) where T : class
        {
            //use Linq to get the Count of String Memeber
            int iret;
            iret = 0;
            PropertyInfo[] oProp = source.GetType().GetProperties();
            foreach (PropertyInfo prop in oProp)
            {
                if (prop.PropertyType.Name == "String")
                {
                    iret++;
                }
            }
           

            return iret;
        }
        /// <summary>
        /// Extesnsion Method to Count number of String Member .
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        private static int StringMemeberCount<T>(this T source) where T : class
        {
           //use Linq to get the Count of String Memeber
            
            int iret = (from a in source.GetType().GetProperties()
                        where a.PropertyType.Name == "String"
                        select a).Count();

            return iret;
        }
        /// <summary>
        /// This method will be invoke method in runtime based on number of pa
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        private static string overloadCall<T>(  T source,int param) where T : class
        {
            MethodInfo mi = (from a in source.GetType().GetMethods()
                             where a.Name == "myMethod" && a.GetParameters().Length == param 
                             select a).FirstOrDefault();
            if (param == 1) { object[] arguments = { 1 }; return mi.Invoke(source, arguments).ToString(); }
            if (param == 2) { object[] arguments = { 1, "abz" }; return mi.Invoke(source, arguments).ToString(); }

            return "";
           
            
        }
        private static string overloadCallClassic<T>(T source, int param) where T : class
        {
            MethodInfo mi = source.GetType().GetMethod("myMethod");

            if (param == 1) { object[] arguments = { 1 }; return mi.Invoke(source, arguments).ToString(); }
            if (param == 2) { object[] arguments = { 1, "abz" }; return mi.Invoke(source, arguments).ToString(); }

            return "";


        }
        /// <summary>
        /// Extesnsion Method to Count number of non String Member .
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        private static int nonStringMemeberCount<T>(this T source) where T : class
        {
            //use Linq to get the Count of String Memeber
            int iret = (from a in source.GetType().GetProperties()
                        where a.PropertyType.Name != "String"
                        select a).Count();

            return iret;
        }
        public class person
            
        {
            public person()
    {
      

    }

            public string name { get; set; }
            public string Address { get; set; }
            public string URL { get; set; }
            public string City { get; set; }
            public int pincode { get; set; }
            public int Age { get; set; }
            public int Height { get; set; }
            public DateTime DOB { get; set; }
            public string street { get; set; }
            public string myMethod(int i)
            {
                return "This invoke  method with single Parameter";
            }
            public string myMethod(int i, string j)
            {
                return "This invoke method with double Parameter";
            }

        }


    }
    
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions