List集合的通用Sort扩展

 

      public static IList<T> Sort<T>(this IList<T> source, string sortProper, bool asc)

        {

            if (source != null && source.Any())

            {

                var properties = typeof(T).GetProperties();

                PropertyInfo pro = null;

                foreach (var item in properties)

                {

                    if (item.Name.ToUpper().Equals(sortProper.ToUpper()))

                    {

                        pro = item;

                        break;

                    }

                }

                for (int i = 0; i < source.Count; i++)

                {

                    T t;

                    for (int k = 0; k < source.Count; k++)

                    {

                        int compare = pro.GetValue(source[i], null).ToString().CompareTo(pro.GetValue(source[k], null).ToString());

                        if ((asc && compare <0)||(!asc && compare > 0))

                        {

                            t = source[i];

                            source[i] = source[k];

                            source[k] = t;

                        }

                    }

                }

                return source;

            }

            return null;

        }

  

 

你可能感兴趣的:(list)