Linq Sort(按名称选择道具):定制obj的集合与抽象对象的字典的集合

时间:2019-07-05 15:31:13

标签: c# linq

我目前在VR中实现了一种数据可视化工具,需要支持通过某些用户选择的属性和条件对“数据块”进行排序。我不知道该属性将是什么类型,因此它可能是一个抽象类。

我的问题是关于在保持灵活性的同时实现此功能的最佳方法。

我的基本要求是:

  • 我需要能够使用string之类的东西从GetProperty()中选择属性
  • 我需要能够以最少的更改支持新类型或复杂类型

到目前为止,我想到了两种方法,以下是我放在一起的伪代码:

1)Collection<MyDataBlob> CollectionBlob;

我需要类似的东西:

public abstract class AbstractObj: IComparer<AbstractObj>
{           
    public abstract int Compare(AbstractObja, AbstractObjb);
}

class MyDataBlob 
{
    string prop1;
    int prop2;
    AbstractObj prop3;
}

// adapted from https://stackoverflow.com/questions/47781469/linq-select-property-by-name
// I am not sure how well this will be suited for custom conditions

List<T> GetListOfProperty<T>(IEnumerable<MyDataBlob> colBlobs, string property)
{
    Type t = typeof(MyDataBlob);         
    PropertyInfo prop = t.GetProperty(property);
    return colBlobs
        .Select(blob=> (T)prop.GetValue(blob))
        .Distinct()
        .OrderBy(x => x)
        .ToList();
}

2)Collection<Dictionary<string, MyEncapsulatedType>> CollectionBlob;

其中字典简化了查找属性的步骤,但是没有基础对象。这符合条件吗?

class MyEncapsulatedType : IComparable<MyEncapsulatedType>
{
     myType theType;
     int val1;
     float val2;
     string val3;

     int Compare(MyEncapsulatedType x, MyEncapsulatedType y) {
         // code
     } 

     // use Get<T> to get the type
}

我认为2)非常容易出错且容易出错。 1)似乎更好,但是我不确定以这种方式选择属性是否最佳。

有人可以让我知道这些方法中的任何一种是否有效,如果无效,我该怎么办?

有更好的方法吗?

0 个答案:

没有答案