C# 使用策略设计模式(C)根据不同的数据列进行排序

C# 使用策略设计模式(C)根据不同的数据列进行排序,c#,design-patterns,strategy-pattern,C#,Design Patterns,Strategy Pattern,我目前正试图了解所有不同的设计模式,我已经被设定了根据不同列对IQueryable进行排序的任务,这就是它目前的实现方式: if (choice == 1) { return from Animals in ctx.Animals orderby Animals.AnimalID descending select Animals; } else if (choice == 2) { return from Animals in ctx.Animals orderby An

我目前正试图了解所有不同的设计模式,我已经被设定了根据不同列对IQueryable进行排序的任务,这就是它目前的实现方式:

if (choice == 1)
{ 
    return from Animals in ctx.Animals orderby Animals.AnimalID descending select Animals; 
}
else if (choice == 2)
{ 
    return from Animals in ctx.Animals orderby Animals.Name descending select Animals; 
}
else if (choice == 3)
{ 
    return from Animals in ctx.Animals orderby Animals.Age descending select Animals; 
}

然而,这对我来说似乎是一种糟糕的代码味道,它无法轻松添加不同的字段或排序选项,我的导师建议我最好实施策略模式,并使用字典选择我们想要的策略实施,然而,我不确定战略模式将如何应用于这种情况,任何有用的提示都将不胜感激,如果需要更多信息,请询问

应用策略模式,您将拥有一个ISortStrategy接口,然后是一些实现,如SortById、SortByName和SortByAge。该接口及其实现将具有类似对象SortAnimal animal的方法;返回动物的一个属性

然后,您只需在运行时选择适当的策略,并按如下方式使用它:

return from animal in ctx.Animals
       orderby sortStrategy.Sort(animal) descending
       select animal;

继续@dcastro的回答,关于字典

您可以通过factory类创建具体策略,并通过使用factory获得奖励积分:

public static class SortStrategyFactory()
{
    private static Dictionary<string, ISortStrategy> strategyRepository;

    static SortStrategyFactory()
    {
      strategyRepository = new Dictionary<string, ISortStrategy>();
      strategyRepository.Add("ID", new SortById());
      strategyRepository.Add("Name", new SortByName());
      strategyRepository.Add("Age", new SortByAge());
    }

    public static ISortStrategy GetStrategy(string key)
    {
      //todo: add error checking
      return strategyRepository[key];
    }

}

dcastro的回答很好。他给了你所有的暗示。从那一点开始,你必须自己做。谢谢你的回答,我想我知道我现在要做什么了,我唯一的问题是我不知道我被告知要使用的字典是如何发挥作用的,这与选择我使用的接口的哪个实现有关吗?@user2879468是的,你可以做一些像Dictionary这样的事情来存储不同的排序策略,然后从用户输入中查询它,比如ISortStrategy strategy=myDictionary[userInput],我猜字典将用于索引所有可用的策略。。选择是否来自用户输入?我想他希望你有一个IDictionary,其中键是一个标识符,例如姓名、年龄。用户将输入名称,您将使用该字符串在字典中查找正确的策略。谢谢,这正是我要查找的内容!:我已经把你的答案标记为正确答案,非常感谢。
ISortStrategy sortStrategy= SortStrategyFactory.GetStrategy(choice);

return from animal in ctx.Animals
       orderby sortStrategy.Sort(animal)
       descending select animal;