LINQのクエリ構文とメソッド構文
今日C#で学んだことはLINQのクエリ構文とメソッド構文についてです。
正直なんで構文を2つ用意したのか分かりません。
あえて言うならクエリ構文が今までのC#の文法と比べてあまりにも異質だったからなんでしょうかね。
LINQのクエリ構文とメソッド構文の書き方
コード
下記のコードがLINQのクエリ構文とメソッド構文の書き方です。
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var scores = new[]
{
new { Name = "Mary", Subject="History", Score = 50 },
new { Name = "John", Subject="History", Score = 80 },
new { Name = "John", Subject="Physics", Score = 60 },
new { Name = "Mary", Subject="Physics", Score = 90 },
new { Name = "John", Subject="Art", Score = 40 },
new { Name = "Mary", Subject="Music", Score = 85 },
new { Name = "Tom", Subject="Music", Score = 50 },
};
// query syntax
var query1 =
from score in scores
where score.Score >= 60
orderby score.Score
select score;
Console.WriteLine($"query syntax output:");
foreach (var res in query1)
{
Console.WriteLine($"{ res.Name } got { res.Score } for { res.Subject }. ");
}
// method syntax
var method1 = scores.Where(s => s.Score >= 60).OrderBy(s => s.Score);
Console.WriteLine($"method syntax output:");
foreach (var res in method1)
{
Console.WriteLine($"{ res.Name } got { res.Score } for { res.Subject }. ");
}
// query syntax
var query2 =
from score in scores
group score by score.Name into scoreGroup
orderby scoreGroup.Key descending
select scoreGroup;
Console.WriteLine($"query syntax output:");
foreach (var res in query2)
{
Console.WriteLine($"{ res.Key }'s max score is { res.Max(s => s.Score) }. ");
}
// method syntax
var method2 = scores.GroupBy(s => s.Name).OrderByDescending(g => g.Key);
Console.WriteLine($"method syntax output:");
foreach (var res in method2)
{
Console.WriteLine($"{ res.Key }'s max score is { res.Max(s => s.Score) }. ");
}
}
}
クエリ構文とメソッド構文の書き換え自体はそれほど難しくなさそうなので、どちらかを覚えておけば大丈夫だと思います。
実行結果
上記のコードの実行結果は下記になります。
query syntax output:
John got 60 for Physics.
John got 80 for History.
Mary got 85 for Music.
Mary got 90 for Physics.
method syntax output:
John got 60 for Physics.
John got 80 for History.
Mary got 85 for Music.
Mary got 90 for Physics.
query syntax output:
Tom's max score is 50.
Mary's max score is 90.
John's max score is 80.
method syntax output:
Tom's max score is 50.
Mary's max score is 90.
John's max score is 80.
今後どっちの構文を使っていくか迷いますね。見た感じはメソッド構文の方が慣れている書き方ですけどね。まぁどっちを使うにしても統一して使っていこうと思います。