johnllao

July 9, 2009

Generic method for Sorting Collection

Filed under: Uncategorized — johnllao @ 5:43 pm

In this blog I would like to show a code perform sorting from a generic collection of type List<T>. This code has been always in my utility classes I used from most of my projects.

Also in the following codes I demonstrated the CompareFields function that can perform Compare operations to any promitive types in .Net CLR

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="field_name"></param>
        /// <param name="mode"></param>
        /// <param name="item1"></param>
        /// <param name="item2"></param>
        /// <returns></returns>
        public static int CompareFields<T>(string field_name, string mode, T item1, T item2)
        {
            Type type = typeof(T);
            PropertyInfo property = type.GetProperty(field_name);
            MethodInfo compareMethod = property.PropertyType.GetMethod("CompareTo", new Type[] { typeof(object) });

            object v1 = property.GetValue(item1, null);
            object v2 = property.GetValue(item2, null);

            int r;
            if (mode == "A")
            {
                r = Convert.ToInt32(compareMethod.Invoke(v1, new object[] { v2 }));
            }
            else
            {
                r = Convert.ToInt32(compareMethod.Invoke(v2, new object[] { v1 }));
            }
            return r;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collection"></param>
        /// <param name="field_name"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public static void SortCollection<T>(List<T> collection, string field_name, string mode)
        {
            collection.Sort(
                    delegate(T item1, T item2)
                    {
                        return CompareFields<T>(field_name, mode, item1, item2);
                    }
                );
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collection"></param>
        /// <param name="field_name"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public static void SortCollection<T>(List<T> collection, string field_name)
        {
            SortCollection<T>(collection, field_name, "A");
        }

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

You must be logged in to post a comment.

Blog at WordPress.com.