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

WBOY
Release: 2023-09-22 17:33:07
forward
1325 people have browsed it

如何在 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");
Copy after login

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")
};
Copy after login

Array tuple

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

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)
{
}
Copy after login

Tuple as return type

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template