c# - 带有 String keySelector 的 OrderBy

标签 c# .net linq lambda

我有以下函数,它根据对象的属性提取不同的值,这里是客户端。

    public List<DistinctValue> GetDistinctValues(string propertyName)
    {
        //how should I specify the keySelector ?
        Func<string, object> keySelector = item => propertyName;

        var list = new List<DistinctValue>();
        var values = this.ObjectContext.Clients.Select(CreateSelectorExpression
                              (propertyName)).Distinct().OrderBy(keySelector);
        int i = 0;
        foreach (var value in values)
        {
            list.Add(new DistinctValue() { ID = i, Value = value });
            i++;
        }

        return list;
    }

    private static Expression<Func<Client, string>> CreateSelectorExpression
                                                        (string propertyName)
    {
        var paramterExpression = Expression.Parameter(typeof(Client));
        return (Expression<Func<Client, string>>)Expression.Lambda(
             Expression.PropertyOrField(paramterExpression, propertyName), 
                                                   paramterExpression);
    }

public class DistinctValue
{
    [Key]
    public int ID { get; set; }
    public string Value { get; set; }
}

我这样做是因为我不知道我需要提取哪些属性值。 它正在运行,只是结果未排序。

能否请您帮我更正排序以使 OrderBy 按预期工作?

属性是字符串,我不需要链式排序。我也不需要指定排序顺序。

非常感谢, 约翰。

最佳答案

您的 keySelector 当前为每个(属性名称)返回相同 字符串;由于 LINQ 通常是一种稳定的排序,因此不会导致整体变化。由于您已经投影到字符串值,因此您可以在此处简单地使用简单的 x=>x 映射:

var values = this.ObjectContext.Clients.Select(
    CreateSelectorExpression(propertyName)).Distinct().OrderBy(x => x);

按商品本身订购

关于c# - 带有 String keySelector 的 OrderBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4658138/

相关文章:

c# - 在 HTML 中,这个属性的名称是什么?

Linq 到实体参数化构造函数 Datetime

c# - linq - 如何查询一个查询源中不在另一个查询源中的项目?

c# - LINQ左外连接查询错误: OuterApply did not have the appropriate keys

c# - Prism 5 模块化 : how to add RegionName in DataTemplate of TabControl in ItemsControl

c# - 使用 Entity Framework 6.1 CodeFirst 的 SQL Server 2014 内存优化表

c# - .NET - 扩展列表类中的 FindIndex() 编译错误

c# - 取消线程任务

c# - Linq Groupby Sum 一个嵌套的可观察集合

c# - 基于接口(interface)的全局过滤器