Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you name C# 7 Tuple items inline?

Tags:

c#

tuples

c#-7.0

By default, when using C# 7 tuples, the items will named like Item1, Item2, and so on.

I know you can name tuple items being returned by a method. But can you do the same inline code, such as in the following example?

foreach (var item in list1.Zip(list2, (a, b) => (a, b)))
{
    // ...
}

In the body of the foreach, I would like to be able to access the tuple at the end (containing a and b) using something better than Item1 and Item2.

like image 464
Gigi Avatar asked Apr 27 '17 09:04

Gigi


People also ask

Can you name your child symbols?

The law bans names that contain “obscenity, numerals, symbols, or a combination of letters, numerals, or symbols…”, but naming a child after a mass murderer is A-OK. In most cases, the United States is pretty relaxed about what you can name your child when it comes to the stigma or meaning a name may carry.

Can you name your kid 7?

The name Seven is both a boy's name and a girl's name of English origin. Only if your preceding children are named One, Two, Three, Four, Five, and Six. Erykah Badu and Andre 3000 broke that rule when naming their son.


1 Answers

Yes, you can, by deconstructing the tuple:

foreach (var (boo,foo) in list1.Zip(list2, (a, b) => (a, b)))
{
    //...
    Console.WriteLine($"{boo} {foo}");
}

or

foreach (var item in list1.Zip(list2, (a, b) => (a, b)))
{
    //...
    var (boo,foo)=item;
    Console.WriteLine($"{boo} {foo}");
}

Even if you named the fields when declaring the tuple, you'd need the deconstruction syntax to access them as variables:

foreach (var (boo,foo) in list1.Zip(list2, (a, b) => (boo:a, foo:b)))
{
    Console.WriteLine($"{boo} {foo}");
}

If you want to access the fields by name without deconstructing the tuple, you'll have to name them when the tuple is created:

foreach (var item in list1.Zip(list2, (a, b) => (boo:a, foo:b)))
{
    Console.WriteLine($"{item.boo} {item.foo}");
}
like image 115
Panagiotis Kanavos Avatar answered Oct 20 '22 05:10

Panagiotis Kanavos