2011-12-28 60 views
4

有這麼多類似的問題,但我沒有看到一個適合我的情況......排序IEnumerable的使用LINQ

我不知道爲什麼這不起作用排序前提對象的IEnumerable :

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

我傳遞一個有效p.property爲排序依據的說法和「升序」或「降序」爲中將sortOrder參數

如果我不能「動態化」我在LINQ像這樣的有限時尚,除了一個醜陋的Switch語句或者其他什麼外,還有什麼替代方案那樣?

非常感謝您的時間。

+0

不應該參數的String.format是p.OrderBy和p.sortOrder? – 2011-12-28 04:36:23

+2

動態LINQ OrderBy是由Marc Gravell在[本答案] [1]中爲IEnumerable給出的。 [1]:http://stackoverflow.com/questions/41244/dynamic-linq-orderby – hypermush 2011-12-28 04:37:07

+0

好像對我最好的解決方案是使用馬克的代碼由hypermush的建議。 – theog 2011-12-28 20:55:27

回答

2

我想你是結合查詢符號和點符號。對於這一點,儘量堅持只點符號:

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

我認爲你需要引用pstring.Format()調用內部,就像這樣:

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); 
     }