代码之家  ›  专栏  ›  技术社区  ›  Ananda G

如何根据未知动态泛型列表排序?

  •  2
  • Ananda G  · 技术社区  · 9 年前

    更新日期:

        public class GenericDataAccess<TEntity> : IGenericRepository<TEntity> where TEntity : class
        {
            internal ELearningDBContext ELearningDBContext;
            internal DbSet<TEntity> ELearningDBSet;
    
            public GenericDataAccess(ELearningDBContext context)
            {
                this.ELearningDBContext = context;
                this.ELearningDBSet = context.Set<TEntity>();
            }
            public virtual PagingModel<TEntity> GetAllPaged(int pagesize, NameValueCollection queryString)
            {
                return ELearningDBSet.AsQueryable().ToList();
            }
         }
    

    TEntity Entity 已命名 Id . 所以我想对每个模型进行排序 身份证件 在里面 descending

    我试过这种方法。但它并不有效,而且,它产生了一个例外。

    ELearningDBSet.AsQueryable()..OrderByDescending(i=>typeof(TEntity).GetProperty("Id")).ToList();
    

    我已经回答了这些问题 Q1 , Q2 , Q3 , Q4 C# 密码我们高度赞赏任何一种完美的解决方案。非常感谢。

    3 回复  |  直到 9 年前
        1
  •  2
  •   Ananda G    9 年前

    哇!我刚刚找到了一个很好的解决方案。我刚刚用过。

     ELearningDBSet.AsQueryable().SortBy("Id" + " Desc").ToList();
    

    这里是 SortBy() System.Web.UI.WebControls.QueryExtensions . 有关更多详细信息,请参阅 here . 真的,这对我来说是一个极好的解决方案。

        2
  •  2
  •   aaronR    9 年前

    public interface IEntityBase
    {
        long Id { get; set; }
    }
    

    然后在数据类中,在您的情况下 TEntity ,实现 IEntityBase 界面

    public partial class MyTEntity: IEntityBase
    {
        public long Id { get; set; }
    
        //Other attributes as needed.
    }
    

    在泛型类中 GenericDataAccess<TEntity> 添加约束以使TEntity实现新接口 IEntityBase公司 . 然后在 GetAllPaged OrderByDescending()

    public class GenericDataAccess<TEntity> : IGenericRepository<TEntity> where TEntity : class, IEntityBase
        {
            internal ELearningDBContext ELearningDBContext;
            internal DbSet<TEntity> ELearningDBSet;
    
            public GenericDataAccess(ELearningDBContext context)
            {
                this.ELearningDBContext = context;
                this.ELearningDBSet = context.Set<TEntity>();
            }
            public virtual PagingModel<TEntity> GetAllPaged(int pagesize, NameValueCollection queryString)
            {
                return ELearningDBSet.AsQueryable().OrderByDescending(o => o.Id).ToList();
            }
         }
    

    更新日期: 添加了 partial 的描述符 MyEntity

        3
  •  1
  •   ASpirin    9 年前

    你可以建立一个 Expression tree

    public static IQueryable<T> Sort<T>(this IQueryable<T> source, string field)
    {
        var p = Expression.Parameter(typeof(T));
        var exp = Expression.Property(p, field);
        return source.OrderBy(Expression.Lambda<Func<T, object>>(exp, p));
    }