0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SelectとToArrayで配列を一気に変換【C#】

Last updated at Posted at 2024-10-24

目次

  • 初めに
  • まずはfor文で変換
  • 一気に変換!
    • Selectメソッドとは
    • ToArrayメソッドとは

初めに

今回は、配列の変換を簡潔に書く方法を紹介します。

まずはfor文で変換

まず、LINQを使わずにfor文で変換する方法を見てみましょう。

string[] stringArray = { "1", "2", "3" };

int[] intArray = new int[stringArray.Length];

for (int i = 0; i < stringArray.Length; i++)
{
    intArray[i] = int.Parse(stringArray[i]);
}

冗長に見える反面、処理を追加しやすいというメリットもあります。

一気に変換!

string[] stringArray = { "1", "2", "3" };

int[] intArray = stringArray.Select(int.Parse).ToArray();

非常に簡潔で、可読性が高いですね:laughing:
デバッグはループのステップを確認できるfor文の方が簡単です。

int[] intArray = stringArray.Select(s => int.Parse(s)).ToArray();

ちなみに、こう書くこともできます。
メソッドグループを使うかラムダ式を使うかの違いです。これについても、後日デリケートの記事で触れようと思います。

最後に、Selectメソッド・ToArrayメソッドについても軽く解説します。

Selectメソッドとは

C#の機能であるLINQの一部です。
各要素に変換処理を行います。元のデータを変更せずに、IEnumerable<T>型のシーケンスを作ることができます。便利ですね:relaxed:

IEnumerable<T>型はforeachなどで要素を順に列挙することができます。インデックスで要素に直接アクセスできない点が配列との違いです!

ToArrayメソッドとは

C#の機能であるLINQの一部です。
IEnumerable<T>型を配列に変換してくれます!

0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?