2009-10-22 4 views
22

LINQでは、条件付きのソート順(昇順/降順)を使用できますか?このようなLINQにおける条件付きの "orderby"ソート順

何か(いない有効なコード):

bool flag; 

(from w in widgets 
where w.Name.Contains("xyz") 
orderby w.Id (flag ? ascending : descending) 
select w) 

答えて

25

あなたはインクリメンタル式を作成した場合、あなたがこれを行うことができます。 (あなたが1をリストしていないため、ウィジェットのpropertyは一種の基本であると仮定。)

var x = widgets.Where(w => w.Name.Contains("xyz")); 
if (flag) { 
    x = x.OrderBy(w => w.property); 
} else { 
    x = x.OrderByDescending(w => w.property); 
} 

+0

それらが必要とされているかどうか動的条件で複数の注文を行う方法。 – Ruchan

+0

'OrderBy'と' ThenBy'の結果に異なる変数を使用して、異なる戻り値の型を保持する必要があります。それ以外の場合は、適切な 'ThenBy'または' ThenByDescending' LINQ演算子にコールを追加してください。 – Richard

8

あなたはご注文後、発注せずにベースクエリを定義することができます。一般的には簡単に表現ではなく、理解の表現を使用してフラグに従って:

var query=(from w in widgets 
    where w.Name.Contains("xyz") 
    select w); 

var result = flag ? 
    query.OrderBy(w =>w) : 
    query.OrderByDescending(w = w); 
8

次のような何かを試みることができる:

var q = from i in list 
     where i.Name = "name" 
     select i; 
if(foo) 
    q = q.OrderBy(o=>o.Name); 
else 
    q = q.OrderByDescending(o=>o.Name); 
14

...または発注プロパティIdが数である(または単項マイナスをサポートしている)場合は1つの文

bool flag; 

var result = from w in widgets where w.Name.Contains("xyz") 
    orderby 
    flag ? w.Id : 0, 
    flag ? 0 : w.Id descending 
    select w; 
+0

基礎となるデータがSQLの場合、この答えはSQLのORDERBY句を使用する可能性が最も高いようですが、事実についてはわかりません。 –

1

でそれをすべて行う1も行うことができます:

bool ascending = ... 

collection.Where(x => ...) 
    .OrderBy(x => ascending ? x.Id : -x.Id) 
    .Select(x => ...) 

// LINQ query 
from x in ... 
orderby (ascending ? x.Id : -x.Id) 
select ... 
0

MoreLINQ NuGet packageは、thisをより便利にする拡張方法も提供します。 これはさらに多くの便利な拡張メソッドを提供し、したがって私のプロジェクトでは安定したものになります。

3

これは、式の流れを壊さずに、さまざまな条件付きラムダ式に使用できる、より一般的な解です。

public static IEnumerable<T> IfThenElse<T>(
    this IEnumerable<T> elements, 
    Func<bool> condition, 
    Func<IEnumerable<T>, IEnumerable<T>> thenPath, 
    Func<IEnumerable<T>, IEnumerable<T>> elsePath) 
{ 
    return condition() 
     ? thenPath(elements) 
     : elsePath(elements); 
} 

あなたも、より複雑な順序付けを行うと、まだ短い、それを維持することができ

var result = widgets 
    .Where(w => w.Name.Contains("xyz")) 
    .IfThenElse(
     () => flag, 
     e => e.OrderBy(w => w.Id), 
     e => e.OrderByDescending(w => w.Id)); 
0

var dict = new Dictionary<int, string>() { [1] = "z", [3] = "b", [2] = "c" }; 
    var condition = true; 
    var result = (condition ? dict.OrderBy(x => x.Key) : dict.OrderByDescending(x => x.Value)) 
     .Select(x => x.Value);