2014-03-27 83 views
0

我有一个基类的列表。每个派生类都有其独特的需求,用于对基类中的公共列表进行排序。为此,我想在基类中创建一个获取字符串的方法。该字符串包含一个自定义的"OrderBy"查询。C#语法从字符串

相反的:

protected void SortBaseClassList(string orderByQueryString) 
{ 
    List<MyBaseClass> sortedList = BaseClassList.OrderByDescending(x => x.GetTop) 
               .ThenBy(x => x.GetLeft) 
               .ToList<MyBaseClass>(); 
} 

我想用:

protected void SortBaseClassList(string orderByQueryString) 
    { 
     List<MyBaseClass> sortedList = 
      BaseClassList. + orderByQueryString + .ToList<MyBaseClass>(); 
    } 

这可能吗?如果是这样,我该怎么做?

+0

哪里查询字符串从何而来?当你说它是* custom *时,你的意思是*自定义*如输入/用户可配置,或*自定义*,如静态取决于正在排序的类? –

+1

难道你不能只使用键字典作为queryString和价值作为lambda为了排序,然后在你的方法find元素与该键并使用lambda? – kosnkov

+0

@ O.R.Mapper Custom是派生类的唯一定制orderBy查询。 – user3165438

回答

1

您似乎需要MyBaseClass的每个子类的一组特定的排序规则。这正是类层次结构中的多态性所在,您可以通过执行IComparable<T> interface来使用它。

添加一个抽象实现你的基类:

public abstract class MyBaseClass : IComparable<MyBaseClass> 
{ 
    // ... 

    public abstract int CompareTo(MyBaseClass other); 
} 

然后,在每个子类中,以应用特定的子类排序以适当的方式覆盖CompareTo。下面是一个典型的子类:

public class MySubClass : MyBaseClass 
{ 
    // ... 

    public int SomeValue { get; set; } 

    public override int CompareTo(MyBaseClass other) 
    { 
     if (other == null) { 
      // every instance comes after null, cf. docs 
      return 1; 
     } 

     var typedOther = other as MyBaseClass; 
     if (typedOther != null) { 
      // other instance of same type; compare by custom sorting criteria 
      return this.SomeValue.CompareTo(typedOther.SomeValue); 
     } else { 
      // other instance of different type; make sure different types are always sorted in the same order 
      return GetType().FullName.CompareTo(other.GetType().FullName); 
     } 
    } 
} 

这样做的副作用是,你不需要LINQ OrderBy方法了;您现在可以直接调用就行了Sort(不指定任何额外的,如比较器)和排序就地而不是创建一个新的列表:

BaseClassList.Sort();