佐々木屋

技術的なことから趣味まで色々書きます

LINQを始める前に・・・

LINQを始める前にいくつか基礎知識として情報を紹介しておきます。

SQLとの関連

LINQ to Objectにおいて、構文がSQLと似ていますが、SQLと一切関係はありません。例えば、

int[] values = { 1, 2, 3, 4, 5 };

var q = from x in values
        where x % 2 == 0
        orderby x
        select x * 3;
Dim values As Integer() = {1, 2, 3, 4, 5}

Dim q = From x In values
        Where x Mod 2 = 0
        Order By x
        Select x * 3

こんな感じでSQLでおなじみのキーワードが出てきますが全く関係ないです。ただ、意味としてはSQLとほぼ同じと考えて良いでしょう。

速度

よく「LINQは遅い」という記事を見ますが、どれくらい遅いか確認してみましょう。10万個の数値配列にすべて2をかけてListコレクションに再格納してみます。

int[] values = Enumerable.Range(1, 100000).ToArray();

//foreach
{
    Stopwatch sw = new Stopwatch();
    List<int> res = new List<int>();
    sw.Start();
    foreach (int v in values) {
        res.Add(v * 2);
    }
    sw.Stop();
    Console.WriteLine(sw.Elapsed);
}

//LINQ
{
    Stopwatch sw = new Stopwatch();
    List<int> res = new List<int>();
    sw.Start();
    res = values.Select(x => x * 2).ToList();
    sw.Stop();
    Console.WriteLine(sw.Elapsed);
}
Dim values As Integer() = Enumerable.Range(1, 100000).ToArray()

'For Each
With Nothing
    Dim sw As New Stopwatch
    Dim res As New List(Of Integer)
    sw.Start()
    For Each v As Integer In values
        res.Add(v * 2)
    Next
    sw.Stop()
    Console.WriteLine(sw.Elapsed)
End With

'LINQ
With Nothing
    Dim sw As New Stopwatch
    Dim res As New List(Of Integer)
    sw.Start()
    res = values.Select(Function(x) x * 2).ToList()
    sw.Stop()
    Console.WriteLine(sw.Elapsed)
End With
00:00:00.0014226
00:00:00.0049621

確かにforeach文の方が速度に分があるようです。しかし、10万回の処理でその差は0.004秒以下となり、そこまで気にするほどの遅さではありません。

文法

LINQの文法は最初のSQLとの関連で紹介した「クエリ構文」と、速度で紹介した「ラムダ式を利用したメソッド構文」がありますが、現在は後者である「ラムダ式を利用したメソッド構文」が主流です。