Jon*_*onx 5 .net c# linq lambda
我有以下函数,它根据对象的属性(此处为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; }
}
Run Code Online (Sandbox Code Playgroud)
我这样做是因为我不知道在哪个属性值之前我需要提取.它正在工作,只是结果没有排序.
您能否帮我纠正排序,使OrderBy按预期工作?
属性是字符串,我不需要链接排序.我也不需要指定排序顺序.
非常感谢,约翰.
您keySelector
当前为每个(属性名称)返回相同的字符串; 由于LINQ通常是一种稳定的排序,因此不会导致整体变化.由于您已经预测了字符串值,因此您可以x=>x
在此处使用简单的映射:
var values = this.ObjectContext.Clients.Select(
CreateSelectorExpression(propertyName)).Distinct().OrderBy(x => x);
Run Code Online (Sandbox Code Playgroud)
由物品本身订购.
小智 6
感谢优雅的解决方案.我进一步扩展了CreateSelectorExpression方法,因此可以在上面的示例中在Client类之外使用它.
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);
}
Run Code Online (Sandbox Code Playgroud)
用法
Func<IQueryable<YourEntity>, IOrderedQueryable<YourEntity>> orderBy = o => o.OrderByDescending(CreateSelectorExpression<YourEntity>("Entity Property Name"));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7137 次 |
最近记录: |