我需要一个返回keySelector的方法,该方法可以在调用OrderBy表达式时使用。问题是keySelector是泛型委托,我希望该方法在TKey上返回具有不同数据类型的keySelector:

Func<TSource,TKey> keySelector


我想做到这一点,但是不是使用lambda表达式,而是返回keySelector(TKey = string或int)的方法:

IEnumerable<Person> orderedByFirstName = persons.OrderBy(p => p.FirstName);
IEnumerable<Person> orderedByAge = persons.OrderBy(p => p.Age);


是否有可能以某种方式在TKey上返回具有不同类型的keySelector的方法?返回lambda表达式是不可能的,但是类似的东西...

只要该方法仅返回数据类型为string的keySelector,一切就可以正常工作:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

public class Behavior
{
    public virtual string GetOrderByKeySelector(Person p)
    {
        return p.FirstName;
    }
}

public class SpecializedBehavior : Behavior
{
    public override string GetOrderByKeySelector(Person p)
    {
        return p.LastName;
    }
}

List<Person> persons = new List<Person>
{
    new Person{Age=10, FirstName="Pelle", LastName="Larsson"},
    new Person{Age=90, FirstName="Nils", LastName="Nilsson"},
    new Person{Age=15, FirstName="Olle", LastName="Johansson"},
    new Person{Age=30, FirstName="Kalle", LastName="Svensson"}
};


像这样使用:

SpecializedBehavior behavior = new SpecializedBehavior();
IEnumerable<Person> orderedResult = persons.OrderBy(behavior.GetOrderByKeySelector);

最佳答案

取而代之的是将集合带入方法。

void Main()
{
    SpecializedBehavior behavior = new SpecializedBehavior();
    IEnumerable<Person> orderedResult = behavior.Sort(persons);
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

public class Behavior
{
    public virtual IEnumerable<Person> Sort(IEnumerable<Person> persons)
    {
        return persons.OrderBy(p => p.FirstName);
    }
}

public class SpecializedBehavior : Behavior
{
    public override IEnumerable<Person> Sort(IEnumerable<Person> persons)
    {
        return persons.OrderBy(p => p.Age);
    }
}


List<Person> persons = new List<Person>
{
    new Person{Age=10, FirstName="Pelle", LastName="Larsson"},
    new Person{Age=90, FirstName="Nils", LastName="Nilsson"},
    new Person{Age=15, FirstName="Olle", LastName="Johansson"},
    new Person{Age=30, FirstName="Kalle", LastName="Svensson"}
};

10-04 16:57