5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

LinqでのSelectとWhereとの違い

Posted at

C#のLinqでのSelectとWhereの違いについてみてみます。

1、Select
「Select」は、リストや配列の各要素を順番に処理するイメージです。
例えば、以下の通りです。

using System;
using System.Linq;
using System.Collections.Generic;
public class Sample {
    
    static public void Main () {
        
        int[] numbers = new int[]{1, 2, 3, 4, 5};
        
        // 各数値を3倍する
        IEnumerable<int> it = numbers.Select(item => item * 3);
        
        foreach(int item in it) {
            Console.WriteLine(item);
        }
        
    }
}

//出力結果
3
6
9
12
15

2、Where
「Where」は、条件に合致したデータを抽出するイメージです。
例えば、以下の通りです。

using System;
using System.Linq;
using System.Collections.Generic;
public class Sample {
    
    static public void Main () {
        
        int[] numbers = new int[]{1, 2, 3, 4, 5};
        
        // 偶数のみを抽出する
        IEnumerable<int> it = numbers.Where(item => item % 2 == 0);
        
        foreach(int item in it) {
            Console.WriteLine(item);
        }
        
    }
}

//出力結果
2
4

3、Selectのおまけ
Selectは各要素が条件を満たしているかの判定する機能もあります。

using System;
using System.Linq;

//trueかflaseの判定 
class Program
{
    static void Main(string[] args)
    {
        int[] numbers = new int[] {1,2,3,4,5,6};
        //4の倍数かどうかを判定する
        var olds = numbers.Select(x => x % 4 == 0);
        foreach(var old in olds)
        {
            Console.WriteLine(old);
        }
    }
}

//出力結果
False
False
False
True
False
False

参照記事
https://symfoware.blog.fc2.com/blog-entry-1928.html
https://csharpprogram.com/category/c/linqpractice/

5
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?