1
1

More than 3 years have passed since last update.

匿名型とタプル

Posted at

長い間、匿名型とタプルを同じものだと思い込んでいたため、反省と備忘録をこめて記事を作成しました。

匿名型

List<string> strList = new List<string>() { "AAA", "BBB", "CCC", "DDD", "EEE"};

//anoはタプルではない!匿名型
var ano = strList.Select((str, index) => new { str, index });

上記のような記載をした場合、anoはタプルのリストではなく匿名型のリストとなります。
そのため、以下のような代入はできません。

//↓NG : '<anonymous type: string str, int index>'を'(string str, int index)'に暗黙的に変換できません
//(string str, int index) val = ano.FirstOrDefault();

タプル

List<string> strList = new List<string>() { "AAA", "BBB", "CCC", "DDD", "EEE"};

//tupはタプル!
var tup = strList.Select((str, index) => (str, index));

一方こちらは、タプルのリストとなります。
以下のような代入が可能です。

//↓OK
(string str, int index) val = tup.FirstOrDefault();

補足

本記事ではC#8.0から標準で導入されているValueTupleのことをタプルと呼んでいます。
Visual Studio 2017を使用されている場合、NuGetからValueTupleパッケージをインストールすることで利用可能です。

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