2011-12-28 7 views
4

を使用して:私はしていない「dynamicize」私のLINQはsortOrder引数ソートIEnumerableをそこSO上の多くの類似の質問がありますが、私はこれが前提オブジェクトのIEnumerableををソートするために動作しませんなぜ私は思ったんだけど...</p> <p>を自分の状況に合ったものを見ていないよLINQ

ためORDERBYの引数と「降順」「昇順」またはのためにそして、私はできれば、有効なp.propertyに渡している

sortedPremiseList = from p in premiseList 
       orderby (string.Format("{0} {1}", orderBy, sortOrder)) 
        select p; 

このような限られた方法で、大きな醜いスイッチのステートメントやsomethiの横には何がありますかそんなの?

お時間をありがとうございました。

+0

はString.Formatのにパラメータがp.OrderByとp.sortOrderではないでしょうか? –

+2

動的LINQ OrderByは[この回答] [1]のMarc GravellによってIEnumerableに与えられています。 [1]:私のための最善の解決策は、hypermushにより示唆されるようにマークのコードを使用することであるようにhttp://stackoverflow.com/questions/41244/dynamic-linq-orderby – hypermush

+0

は思えます。 – theog

答えて

2

私は、あなたはクエリ記法とドット表記を組み合わせていると思います。このため、単にドット表記にこだわってみてください。

sortedPremiseList = premiseList 
      .OrderBy(p => string.Format("{0} {1}", p.orderBy, p.sortOrder)); 
1

私はあなたがこのように、あなたのstring.Format()コール内pを参照する必要があると思う:

sortedPremiseList = from p in premiseList 
    orderby (string.Format("{0} {1}", p.orderBy, p.sortOrder)) 
    select p; 
1

私は私はあなたがここに求めているものを理解だと思います。文字列引数からLINQクエリを作成したい場合

いいえ。私は挑戦が好きです。

IComparable GetPropValue(object src, string propName) 
{ 
    return (IComparable)src.GetType().GetProperty(propName).GetValue(src, null); 
} 

IEnumerable<Premise> SortMyPremises(IEnumerable<Premise> premises, string propertyName, string ascendingOrDescending) 
{ 
    return ascendingOrDescending = "ascending" 
    ? premises.OrderBy(p => GetPropValue(p, propertyName)) 
    : premises.OrderByDescending(p => GetPropValue(p, propertyName)); 
} 

あなたがそれを書いた方法がうまくいかない理由は、LINQの式はコンパイル時にコードに変換され、そしてあなたが渡している文字列は、それが実行時まで評価されないということです。

0

これが私の仕事:

public static IEnumerable<TEntity> OrderBy<TEntity>(this IEnumerable<TEntity> source, string orderByProperty, 
          bool desc) 
     { 
      string command = desc ? "OrderByDescending" : "OrderBy"; 
      var type = typeof(TEntity); 
      var property = type.GetProperty(orderByProperty); 
      var parameter = Expression.Parameter(type, "p"); 
      var propertyAccess = Expression.MakeMemberAccess(parameter, property); 
      var orderByExpression = Expression.Lambda(propertyAccess, parameter); 
      var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType }, 
              source.AsQueryable().Expression, Expression.Quote(orderByExpression)); 
      return source.AsQueryable().Provider.CreateQuery<TEntity>(resultExpression); 
     } 
関連する問題

 関連する問題