Home  >  Article  >  Backend Development  >  How to easily initialize a list of tuples in C#?

How to easily initialize a list of tuples in C#?

WBOY
WBOYforward
2023-09-22 17:33:071295browse

如何在 C# 中轻松初始化元组列表?

Tuples can be used when you want a data structure to hold an object with properties, but don't want to create a separate type for it. The Tuple class was introduced in .NET Framework 4.0. A tuple is a data structure that contains a sequence of elements of different data types.

Tuple<int, string, string> person =
new Tuple <int, string, string>(1, "Test", "Test1");

A tuple can only contain up to eight elements. It gives compiler error when you try to include more than eight elements.

List tuple

var tupleList = new List<(int, string)>
{
   (1, "cow1"),
   (5, "chickens1"),
   (1, "airplane1")
};

Array tuple

var tupleArray = new(int, string)[]
{
   (1, "cow1"),
   (5, "chickens1"),
   (1, "airplane1")
};

Nested tuple

var numbers = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9, 10, 11, 12, 13));
Tuple as a Method Parameter
static void DisplayTuple(Tuple<int,string,string> person)
{
}

Tuple as return type

static Tuple<int, string, string> GetTest()
{
   return Tuple.Create(1, "Test1", "Test2");
}

The above is the detailed content of How to easily initialize a list of tuples in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete