知ってると結構便利なLINQについてのあれこれです。
今回はソート編です。(続くとは言っていない)
LINQとは
LINQとは「Language-Integrated Query」の略で
日本語にすると統合言語クエリっていうらしいです。
IEnumerable
LINQの使い方
以下は公式リファレンスのサンプルコードを抜粋したものですが、
5~7行目がLINQを使用している部分になります。
// Specify the data source.
int[] scores = new int[] { 97, 92, 81, 60 };
// Define the query expression.
IEnumerable<int> scoreQuery =
from score in scores
where score > 80
select score;
// Execute the query.
foreach (int i in scoreQuery)
{
Console.Write(i + " ");
}
クエリ構文とメソッド構文
多分宗教戦争が起こるとしたらここでしょう。
先ほどのコードはクエリ構文で書かれており、
もう一つのメソッド構文は以下のように書きます。
int[] scores = new int[] { 97, 92, 81, 60 };
IEnumerable<int> scoreQuery = scores.Where(x => x > 80);
foreach (int i in scoreQuery)
{
Console.Write(i + " ");
}
自分は初めて仕事で使われているのを見たのが
メソッド構文だったのでこっちの方がしっくりきます(*’▽’)
ソートについて
クエリ構文
SQL文書ければ大体わかる感じです。
予約語が全て小文字でなければいけなかったり、
SELECT句が最後だったりとSQLとは全く別物なわけですが…
IEnumerable<int> scoreQuery =
from score in scores
where score > 80
orderby score
select score;
メソッド構文
ソートに関して以下のメソッドが用意されています。
| OrderBy | シーケンスの要素をキーに従って昇順に並べ替えます。 |
|---|---|
| OrderByDescending | シーケンスの要素をキーに従って降順に並べ替えます。 |
| ThenBy | キーに従って昇順のシーケンス内の要素の後続の並べ替えを実行します。 |
| ThenByDescending | キーに従って降順に並べ替え、シーケンス内の要素の後続の並べ替えを実行します。 |
使用してみた例が以下の通りです。
IEnumerable<int> scoreQuery = scores.Where(x => x > 80)
.OrderBy(x => x);
複数キーのソート
勿論、複数キーのソートにも対応しています。
サンプルクラス
以下のPeopleクラスをソートしてみます。
class People
{
public int id;
public string name;
public People(int id, string name)
{
this.id = id;
this.name = name;
}
}
Listクラスを利用しつつidは降順、nameは昇順にソートしてみます。
(ListクラスにはIEnumerable
LINQを使うことができます。)
List<People> peopleList = new List<People>()
{
new People(1, "安藤"),
new People(2, "伊藤"),
new People(3, "A権三郎"),
new People(999, "大樹"),
new People(3, "C権三郎"),
new People(3, "B権三郎"),
new People(0, "新藤")
};
// ソート処理
// ・第1ソート:id(降順)
// ・第2ソート:name(昇順)
var orderedPeople = peopleList.OrderByDescending(q => q.id)
.ThenBy(q => q.name);
Console.WriteLine("■ソート前");
foreach (People pp in peopleList)
{
Console.WriteLine(string.Format("id:{0} name:{1}", pp.id, pp.name));
}
Console.WriteLine("■ソート後");
foreach (People pp in orderedPeople)
{
Console.WriteLine(string.Format("id:{0} name:{1}", pp.id, pp.name));
}
以下の通りにちゃんと実行されています。
■ソート前 id:1 name:安藤 id:2 name:伊藤 id:3 name:A権三郎 id:999 name:大樹 id:3 name:C権三郎 id:3 name:B権三郎 id:0 name:新藤 ■ソート後 id:999 name:大樹 id:3 name:A権三郎 id:3 name:B権三郎 id:3 name:C権三郎 id:2 name:伊藤 id:1 name:安藤 id:0 name:新藤
その2は何年後に書かれることやら(*´з`)

[…] 【C#】LINQの使い方(その1) […]