一行代码交换两个数据的值

在初学时,我们交换数据一般借助中介者模式
temp

int a=10;
int b=20;
int temp=b;
b=a;
int a=temp;

C#元组,提供了简便的写法

int a = 10;
int b = 20;
Console.WriteLine($"Before swap: a = {a}, b = {b}");
// 使用元组交换两个整数的值
(a, b) = (b, a);
Console.WriteLine($"After swap: a = {a}, b = {b}");

除此之外,我们还可以交换字符串

 string s1 = "11111";
 string s2 = "99999";
 Console.WriteLine($"Before swap: s1 = {s1}, s2 = {s2}");
 // 使用元组交换两个string的值
 (s1, s2) = (s2 ,s1);
 Console.WriteLine($"Before swap: s1 = {s1}, s2 = {s2}");

元组的其他用法
1、解构

  var employee = ("John Doe", 30, 50000.0);
  var (name, age, salary) = employee;

2、使用多个值来确定唯一键

  var dictionary = new Dictionary<(string, string), int>();
  dictionary[("apple", "red")] = 1;
  dictionary[("banana", "yellow")] = 2;

3、返回多个值

(int sum, int count) CalculateSumAndCount(IEnumerable<int> numbers)
{
    int sum = 0;
    int count = 0;
    foreach (var number in numbers)
    {
        sum += number;
        count++;
    }
    return (sum, count);
}
posted @ 2024-09-04 22:52  孤沉  阅读(13)  评论(0编辑  收藏  举报