List<T>集合的通用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;
        }

  

原文地址:https://www.cnblogs.com/a546558309/p/2721504.html