通过lambda表达式传递属性,并对其属性进行排序

Gor*_*ran 1 c# generics

我有一个ISomeType列表,其中T包含至少一个IConvertibleProperty类型的属性.例:

IConvertibleProperty
{
    string PropertyA { get; set; }
    string PropertyB { get; set; }
    // etc
}

public class SomeTypeA : ISomeType
{
    public ConvertibleProperty PropertyX { get; set; }
    // etc
}
Run Code Online (Sandbox Code Playgroud)

我需要创建一个泛型函数,我可以通过以下方式调用它:

CustomMethod(list, x => x.PropertyX);
Run Code Online (Sandbox Code Playgroud)

并且将能够在其中实现下一个排序:

protected void CustomMethod<T, TKey>(IList<T> list, Func<T, TKey> expr) where T : ISomeType where TKey : IConvertibleProperty
{
    // example of non-generic sorting (in this case expr = x.PropertyX)
    var sortedList = list.OrderBy(x => x.PropertyX.PropertyA).ThenBy(x => x.PropertyX.PropertyB).ToList();

    // rest of the code
}
Run Code Online (Sandbox Code Playgroud)

这可能吗?

Blo*_*ard 5

我想你正在寻找这个:

var sortedList = list.OrderBy(x => expr(x).PropertyA)
                     .ThenBy(x => expr(x).PropertyB)
                     .ToList();
Run Code Online (Sandbox Code Playgroud)