2011-01-11 4 views
4

私はオブジェクトのプロパティ(ここではClient)に基づいて私に別個の値を抽出する次の関数を持っています。OrderByを文字列keySelectorで使用する

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が正常に動作するように並べ替えを修正してもらえますか?

プロパティは文字列であり、並べ替える必要はありません。ソート順序を指定する必要はありません。

ありがとうございます。 ジョンです。

答えて

7

keySelectorは現在と同じ文字列(プロパティ名)を返します。 LINQは通常安定した並べ替えであるため、全体的な変更はありません。アイテムそのものでを注文する

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

:あなたはすでに文字列値に投影しているので、あなたは単にここに些細なx=>xマッピングを使用することができます。

+0

答えと説明をありがとうございました。それは多くの意味があります。再度、感謝します。 – Jonx

4

エレガントなソリューションをありがとう。 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); 
}  

使用

Func<IQueryable<YourEntity>, IOrderedQueryable<YourEntity>> orderBy = o => o.OrderByDescending(CreateSelectorExpression<YourEntity>("Entity Property Name")); 
関連する問題