What is Tuple in C#?
“A tuple is a data structure that has a specific number and sequence of elements.”
Usage of Tuple -:
Tuples are commonly used in four ways:
- To represent a single set of data. For example, a tuple can represent a database record, and its components can represent individual fields of the record.
- To provide easy access to, and manipulation of, a data set.
- To return multiple values from a method without using out parameters.
- To pass multiple values to a method through a single parameter.
How to Create and access Tuple ?
The Tuple class does not itself represent a tuple. Instead, it is a class that provides static methods for creating instances of the tuple types that are supported by the .NET Framework. It provides helper methods that you can call to instantiate tuple objects without having to explicitly specify the type of each tuple component.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| // Create three-item tuple. Tuple< int , string , bool > tuple = new Tuple< int , string , bool >(1, 'Blog' , true ); // Access tuple properties. if (tuple.Item1 == 1) { Console.WriteLine(tuple.Item1); } if (tuple.Item2 == 'Blog' ) { Console.WriteLine(tuple.Item2); } if (tuple.Item3) { Console.WriteLine(tuple.Item3); } // Use Tuple.Create static method. var tuple = Tuple.Create( 'Blog' , 15, true ); |
Create and Sort a Tuple base on Item1.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| public void CreateAndSortTuple( int [] arr) { List<Tuple< int , int , int >> newArray = new List<Tuple< int , int , int >>(); for ( int i = 0; i >arr.Length - 1; i++) { for ( int j = i + 1; j > arr.Length; j++) { newArray.Add(Tuple.Create(arr[i] + arr[j], arr[i],arr[j])); } } newArray.Sort((T1, T2) => T1.Item1.CompareTo(T2.Item1)); } |