排序依据和String的KeySelectors依据、String、KeySelectors

2023-09-05 01:58:10 作者:你连微笑都假了

我有以下功能,基于对象的属性,这里客户端

I have the following function that is extracting me distinct values based on the properties of an object, here Client.

    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; }
}

我这样做,因为我不知道在这之前的属性值,我需要提取。 它的工作,只是结果进行排序。

I'm doing this because I do not know in before which property values I'll need to extract. It's working, just the result is not sorted.

能否请你帮我纠正排序,使排序依据按预期方式工作?

Can you please help me correct the sorting to make the OrderBy work as expected?

属性是字符串,我不需要链中的排序。我并不需要或者指定的排列顺序。

The properties are strings and I don't need to chain the sorting. I don't need to specify the sorting order either.

感谢很多提前, 约翰。

Thanks a lot in advance, John.

推荐答案

的KeySelectors 目前返回的相同字符串每次(属性名);并且由于LINQ通常是稳定的排序,这导致没有整体改变。既然你已经投射到字符串值,你可以简单地用一个简单的 X =&GT; X 这里映射:

Your keySelector currently returns the same string for each (the property name); and since LINQ is typically a stable sort, this results in no overall change. Since you have already projected to the string values, you can simply use a trivial x=>x mapping here:

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

要订购的由项目本身的。