Introduction
This article demonstrates different scenarios of using Tuple Class in C# .This was quite new to me which I practiced recently.
I was developing a demo application which was supposed to return multiple list Items. To bind each ListItems to respected ComboBox I have to use 2 separate methods as one method had only one return type. To compress my code I then used Tuple Class.
See the below example where the 2nd one was the application I was developing.
Description
Example-1(Add and Multiply 2 value)
- static void Main(string[] args)
- {
- int a = 10;
- int b = 20;
- var result = Add_Multiply(a, b);
- Console.WriteLine(result.Item1);
- Console.WriteLine(result.Item2);
- }
- private static Tuple<int, int> Add_Multiply(int a, int b)
- {
- var tuple = new Tuple<int, int>(a + b, a * b);
- return tuple;
- }
Example-2 (Return List of data in Item wise)
Here I am reading data from a text file which contains country name and country code and want to bind the names and code in a ComboBox. Here is the below code
- public static Tuple<List<string>, List<string>> GetAllData()
- {
- List<string> CountryName = new List<string>();
- List<string> CountryCode = new List<string>();
- using (var sr = new StreamReader(@"Country.txt")) //using System.IO; //Text file in bin/Debug folder of application
- {
- string line;
- while ((line = sr.ReadLine()) != null)
- {
- int index = line.LastIndexOf(" ");
- CountryName.Add(line.Substring(0, index));
- CountryCode.Add(line.Substring(index + 1));
- }
- }
- return new Tuple<List<string>, List<string>>(CountryName,CountryCode);
- }
To bind data in ComboBox
- ddlCountryName.ItemsSource = Helper.GetAllData().Item1; //Helper is the class where GetAllData() is written
- ddlCountryCode.ItemsSource = Helper.GetAllData().Item2;
Note
- You can find the attached sample solution for reference which is developed in WPF.
- I hope you will love to use Tuple class.
Happy coding :) ;)