Using C# foreach tuple
Asked Answered
C

2

20

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>

Cosgrove answered 22/2, 2011 at 7:11 Comment(0)
S
30

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))
{
  ...
}
Subset answered 22/2, 2011 at 7:13 Comment(3)
ahh ))) thank you , my trouble was - I forgot to use "(" after "foreach" :)Cosgrove
I do not know the return type of your method, so int,string was an example. Please let me know the actual return type of that method.Angelenaangeleno
@nCdy - The solution was easier than assumed then ;)Angelenaangeleno
E
20

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

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

}
Eleonoreleonora answered 2/1, 2020 at 17:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.