Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C# foreach tuple

Tags:

c#

tuples

How can I work with tuples in a foreach loop?

The following code doesn't work:

foreach Tuple(x, y) in sql.lineparams(lines)
{

}

sql.lineparams(lines) is array of tuples <int, string>

like image 898
cnd Avatar asked Feb 22 '11 07:02

cnd


People also ask

What is using () in C#?

The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned. A variable declared with a using declaration is read-only.

Why do we need using in C#?

CSharp Online Training The using statement is used to set one or more than one resource. These resources are executed and the resource is released. The statement is also used with database operations. The main goal is to manage resources and release all the resources automatically.

How do I start learning C?

Get started with C. Official C documentation - Might be hard to follow and understand for beginners. Visit official C Programming documentation. Write a lot of C programming code - The only way you can learn programming is by writing a lot of code.


2 Answers

What does the tuple consist of? Types called x and y? In that case, this should be your syntax:

foreach (Tuple<x, y> tuple in sql.lineparams(lines))
{
  ...
}

If the tuple actually consist of other types, like int and string, it will be like this:

foreach (Tuple<int, string> tuple in sql.lineparams(lines))
{
  ...
}

Or, you can let the compiler handle it for you:

foreach (var tuple in sql.lineparams(lines))
{
  ...
}
like image 192
Øyvind Bråthen Avatar answered Oct 22 '22 17:10

Øyvind Bråthen


With C# 7 you can also directly reference the content of the tuple:

foreach ((x xVar, y yVar) in sql.lineparams(lines))
{

}
like image 30
Jamie Kitson Avatar answered Oct 22 '22 17:10

Jamie Kitson