代码之家  ›  专栏  ›  技术社区  ›  si2030

ASP.NET在一个方法中使用Func作为参数来执行orderby和thenby

  •  -1
  • si2030  · 技术社区  · 6 年前

    我正在挣扎着。一个朋友在某个时候写了这篇文章,现在他在另一个州,所以无法帮助扩展这个想法。

    // For index listing.
    // Order function to identify sort direction.
    private IOrderedEnumerable<Client> OrderClients<T>(IEnumerable<Client> clients, Func<Client, T> keySelector, SortDirection sortDirection) {
        return sortDirection == SortDirection.desc
                ? clients.OrderByDescending(keySelector)
                : clients.OrderBy(keySelector);
    }
    

    但是我的要求变了。

    我现在想要一个静态方法,它可以提供一个 IEnumerable<T> <string, SortDirection> 哪里 SortDirection 方向是枚举:

    public enum SortDirection
    {
        asc = 0,
        desc
    }
    

    这是因为字典可能有多达4列可供排序。第一个值总是 orderBy 其他人都是 thenBy .

    public static IOrderedEnumerable<T> OrderAndThenBy(IEnumerable<T> list, Func<T, Dictionary<string, SortDirection>>){}
    

    我想接受一个IEnumerable,然后使用字典中的列按“string”和它应该排序的方向进行排序。

    This answer by Matthias <key = columns, value = sortDirection> IOrderedEnumerable<T> ..

    有人能帮我解释一下这个方法的结构,以及如何使用Func作为一个Dictionary类型参数的方法参数。我现在是在犯错误。。

    因为我没有正确地编写泛型方法参数。。希望有人能帮忙。

    0 回复  |  直到 6 年前
        1
  •  0
  •   demo    6 年前

    您得到错误是因为您需要包含泛型类型 T 在名称后面的方法声明中(参见[1]),如下所示:

    public static IOrderedEnumerable<T> OrderAndThenBy<T>(IEnumerable<T> list, Func<T, Dictionary<string, SortDirection>> sortInfo){}
    

    OrderBy 方法作为字符串,就像您正在尝试的那样,因此您最好保持键选择像在初始 OrderClients 方法。好了,那个 keySelector 是一个需要 Client ,并返回 ,所以 排序 方法知道要按哪个属性进行排序。 现在您有多个属性,这些属性都可能有不同的类型,现在只提供一个类型参数是不够的。但是,由于您也不知道要排序的属性的数量,所以不能静态地定义所有类型参数。 由于不是最干净但简单的解决方法,您可以删除类型,并将委托更改为返回 object 相反 T .

    你可能还在和 Clients

    注意,字典中元素的顺序是未定义的[4],但在这种情况下,顺序很重要,因此您应该将其替换为列表[5]。

    综上所述,你可能会想出一个方法,比如:

    public static IOrderedEnumerable<Client> OrderAndThenBy(IEnumerable<Client> list,  List<KeyValuePair<Func<Broker, object>, SortDirection>> sortInfo) {}
    

    [1] https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-methods

    [2] https://docs.microsoft.com/en-us/dotnet/api/system.func-2?view=netframework-4.8

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/

    [4] https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2

    https://docs.microsoft.com/en-us/dotnet/standard/collections/selecting-a-collection-class