C# 配列またはリストの指定した位置までの値を取得する

  • 作成日 2021.06.21
  • 更新日 2022.03.30
  • C#
C# 配列またはリストの指定した位置までの値を取得する

C#で、配列またはリストの指定した位置までの値を取得するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Microsoft Visual Studio Community 2019 Version 16.7.1

指定した位置までの値を取得

指定した位置までの値を取得するには、Linqの「Take」を使用することで可能です。

// 配列を用意
int[] num = new int[] { 1, 2, 3, 4, 5 };       

// INDEX番号を指定
num.Take(3); // 1, 2, 3, 4

以下は、インデックス番号を指定して指定した位置までの値を取得し、結果を表示するだけのコードとなります。

using System;
using System.Collections.Generic;
using System.Linq;

namespace testapp
{
    class Program
    {
        static void Main(string[] args)
        {                
            // Listを用意
            var list = new List<int> { 1, 2, 3, 4, 5, 1, 2, 3 };

            try
            {                
                IEnumerable<int> num = list.Take(6);

                Console.WriteLine(String.Join(", ", num.Select(v => v)));
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.ToString());             
            }
        }
    }
}

実行結果

以下のように、範囲にないINDEX番号を指定してもエラーにはなりません。

using System;
using System.Collections.Generic;
using System.Linq;

namespace testapp
{
    class Program
    {
        static void Main(string[] args)
        {                
            // Listを用意
            var list = new List<int> { 1, 2, 3, 4, 5, 1, 2, 3 };

            try
            {                
                IEnumerable<int> num = list.Take(10);

                Console.WriteLine(String.Join(", ", num.Select(v => v)));
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.ToString());             
            }
        }
    }
}

実行結果

条件を指定する場合は、「TakeWhile」を使用します。

using System;
using System.Collections.Generic;
using System.Linq;

namespace testapp
{
    class Program
    {
        static void Main(string[] args)
        {                
            // Listを用意
            var list = new List<int> { 1, 2, 3, 4, 5, 1, 2, 3 };

            try
            {                
                IEnumerable<int> num = list.TakeWhile(v => v < 4);

                Console.WriteLine(String.Join(", ", num.Select(v => v)));
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.ToString());             
            }
        }
    }
}

実行結果