不存在字段的动态linq orderBy



我有一个ObservableCollection,它由基类型和派生类型的对象组成。

public class BaseClass    
{
public string First{get;set}
public ObservableCollection<BaseClass> Items {get;set}
}
public class DerivedClass : BaseClass
{
public Second{get;set}
}

用法是:

ObservableCollection<BaseClass> MyList;
MyList.Add(new BaseClass());
MyList.Add(new DerivedClass());

要求是根据不同的属性对该集合进行排序,从而避免";开关箱";我使用了dyanmic orderBy,如:

MyList = new ObservableCollection<BaseClass>(MyList.AsQueryable().OrderBy(field));

MyList实际上是一个树,排序是递归调用的,总共有1000000个项目,所以性能在这里至关重要。我知道动态orderBy比反射更快——获取字段名称的属性值并进行比较。(或者我错了吗?!?(

现在的问题是,派生类型中存在一些属性,但基类型中不存在,因此排序无法正确执行。我如何实现一些比较器来将丢失的字段处理为null/empty?

您可以实现IComparer并检查类型,但它可能不会比另一个解决方案更干净:

public class CustomComparer : IComparer<BaseClass>
{
public int Compare(BaseClass a, BaseClass b)
{
//whatever custom logic you want to use for sorting can be added here 
if (a is DerivedClass ac && b is DerivedClass bc) 
return Compare(ac.DerivedId, bc.DerivedId);
//.. would have to handle a being Derived when b is not, and opposite.
return Compare(a.Id, b.Id);
}
private int Compare(int a, int b)
{
if (a > b)
return 0;
if (a < b)
return -1;
return 1;
}
}
public class BaseClass
{
public int Id { get; set; }
}
public class DerivedClass : BaseClass
{
public int DerivedId { get; set; } // not on base
}

你可以简单地拨打:

CustomComparer comp = new CustomComparer();
list.Sort(comp); // Sort is extension on List, not ObservableCollection

最新更新