带有字符串 keySelector 的 OrderBy

2024-01-29

我有以下函数,它根据对象的属性提取不同的值,这里是 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; }
}

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

您能帮我纠正排序以使 OrderBy 按预期工作吗?

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

预先非常感谢, 约翰。


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

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

订购由物品本身.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

带有字符串 keySelector 的 OrderBy 的相关文章

随机推荐