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