C# 带有字符串键选择器的OrderBy
我有下面的函数,它根据对象的属性提取不同的值,这里是客户机C# 带有字符串键选择器的OrderBy,c#,.net,linq,lambda,C#,.net,Linq,Lambda,我有下面的函数,它根据对象的属性提取不同的值,这里是客户机 public List<DistinctValue> GetDistinctValues(string propertyName) { //how should I specify the keySelector ? Func<string, object> keySelector = item => propertyName; var li
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; }
}
public List getdistinctValue(字符串属性名称)
{
//我应该如何指定keySelector?
Func keySelector=item=>propertyName;
var list=新列表();
var values=this.ObjectContext.Clients.Select(CreateSelectorExpression
(propertyName)).Distinct().OrderBy(键选择器);
int i=0;
foreach(值中的var值)
{
Add(新的DistinctValue(){ID=i,Value=Value});
i++;
}
退货清单;
}
私有静态表达式CreateSelectorExpression
(字符串属性名称)
{
var parametexpression=Expression.Parameter(typeof(Client));
return(Expression)Expression.Lambda(
Expression.PropertyOrField(ParameterExpression,propertyName),
参数表达);
}
公共类差异值
{
[关键]
公共int ID{get;set;}
公共字符串值{get;set;}
}
我这样做是因为我不知道在之前需要提取哪些属性值。
它正在工作,只是结果没有排序
你能帮我纠正一下排序,使OrderBy按预期工作吗
属性是字符串,我不需要链接排序。我也不需要指定排序顺序
提前多谢了,
John.您的
键选择器当前为每个属性返回相同的字符串(属性名称);由于LINQ通常是一种稳定的排序,因此不会导致总体变化。由于已经投影到字符串值,因此可以在此处简单地使用一个普通的x=>x
映射:
var values = this.ObjectContext.Clients.Select(
CreateSelectorExpression(propertyName)).Distinct().OrderBy(x => x);
您可以自行订购。感谢您提供的优雅解决方案。我进一步扩展了CreateSelectorExpression方法,以便可以在上面示例中的客户机类之外利用它
public static Expression<Func<T, string>> CreateSelectorExpression<T>(string propertyName)
{
var paramterExpression = Expression.Parameter(typeof(T));
return (Expression<Func<T, string>>)Expression.Lambda(Expression.PropertyOrField(paramterExpression, propertyName),
paramterExpression);
}
public静态表达式CreateSelectorExpression(string propertyName)
{
var parametexpression=Expression.Parameter(typeof(T));
return(Expression)Expression.Lambda(Expression.PropertyOrField(ParameterExpression,propertyName),
参数表达);
}
用法
Func orderBy=o=>o.OrderByDescending(CreateSelectorExpression(“实体属性名”);
感谢您的回答和解释。这很有道理。再次感谢。
Func<IQueryable<YourEntity>, IOrderedQueryable<YourEntity>> orderBy = o => o.OrderByDescending(CreateSelectorExpression<YourEntity>("Entity Property Name"));