orderby句
プログラミングC# 第6版 8.3.2
ソートされたデータを返します。
以下実行例
using System; using System.Linq; class Foo { public int id; public string name; } class Program { static void Main() { Foo[] fooList = new Foo[] { new Foo() { id = 5 , name = "hanako" }, new Foo() { id = 4 , name = "tarou" }, new Foo() { id = 9 , name = "aiko" }, new Foo() { id = 1 , name = "tarou" }, }; // idの昇順でソート var ret = from foo in fooList orderby foo.id ascending select foo; foreach(var item in ret) { Console.WriteLine("id={0} name={1}",item.id,item.name); } } }
$ main id=1 name=tarou id=4 name=tarou id=5 name=hanako id=9 name=aiko
うまくソートされていますね。ascendingの部分をdescendingに変更すれば降順でソートされます。また省略時は昇順としてソートされます。
次に、複数の条件を指定してソートする場合は以下のようになります。
// nameの昇順でソートした後、idの降順でソートする var ret = from foo in fooList orderby foo.name ascending,foo.id descending select foo;
$ main id=9 name=aiko id=5 name=hanako id=4 name=tarou id=1 name=tarou
さて最後に同様の処理をorderby句を使わずにOrderByメソッドを使った場合の実装例も試しておきましょう。
// nameの昇順でソートした後、idの降順でソートする
var ret = fooList.OrderBy(foo => foo.name)
.ThenByDescending(foo => foo.id)
.Select(foo => foo);
OrderByが昇順ソード、OrderByDescendingが降順ソート用のメソッドになります。
ThenByというのは複数条件のソートを行う場合に使用するメソッドです。
OrderByDescendingと同様に、降順の場合はThenByDescendingメソッドを使用することになります。