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?

C#でtupleを使用してみる

Posted at

1. はじめに

  • C#でtupleを使用したい

2. 開発環境

  • C#
  • Visual Studio 2022
  • .NET 8

3. タプル型とは

"タプル" 機能を使用すると、軽量のデータ構造に複数のデータ要素を簡潔な構文でグループ化できます。 次の例は、タプル変数を宣言して初期化し、そのデータ メンバーにアクセスする方法を示しています。

4. サンプルソース

4.1. 匿名型のタプル型の定義

  • タプル型を定義するには、すべてのデータ メンバーの型と、必要に応じてフィールド名を指定します
  • Item1から連番でタプルの値を取得します
(double, int) t1 = (4.5, 3);
Console.WriteLine($"Tuple with elements {t1.Item1} and {t1.Item2}.");
// Output:
// Tuple with elements 4.5 and 3.

(double Sum, int Count) t2 = (4.5, 3);
Console.WriteLine($"Sum of {t2.Count} elements is {t2.Sum}.");
// Output:
// Sum of 3 elements is 4.5.

4.2. フィールド名付きのタプル型の定義

  • タプルの初期化式またはタプル型の定義でタプル フィールドの名前を明示的に指定します
var t = (Sum: 4.5, Count: 3);
Console.WriteLine($"Sum of {t.Count} elements is {t.Sum}.");

(double Sum, int Count) d = (4.5, 3);
Console.WriteLine($"Sum of {d.Count} elements is {d.Sum}.");

4.3. タプルの代入と分解

  • C# では、次の両方の条件を満たすタプル型間の代入がサポートされます
    • 両方のタプル型に、同じ数の要素がある
    • タプルのそれぞれの位置で、右側のタプル要素の型が対応する左側のタプル要素の型と同じか、暗黙的に変換可能である
(int, double) t1 = (17, 3.14);
(double First, double Second) t2 = (0.0, 1.0);
t2 = t1;
Console.WriteLine($"{nameof(t2)}: {t2.First} and {t2.Second}");
// Output:
// t2: 17 and 3.14

(double A, double B) t3 = (2.0, 3.0);
t3 = t2;
Console.WriteLine($"{nameof(t3)}: {t3.A} and {t3.B}");
// Output:
// t3: 17 and 3.14

4.4. タプルの等値性

  • タプル型は、==!= 演算子をサポートしています。 これらの演算子により、左側のオペランドのメンバーが、タプル要素の順序に従って、右側のオペランドの対応するメンバーと比較されます
(int a, byte b) left = (5, 10);
(long a, int b) right = (5, 10);
Console.WriteLine(left == right);  // output: True
Console.WriteLine(left != right);  // output: False

var t1 = (A: 5, B: 10);
var t2 = (B: 5, A: 10);
Console.WriteLine(t1 == t2);  // output: True
Console.WriteLine(t1 != t2);  // output: False

5. 参考文献

0
0
0

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?