Skip to main content
Make more clear how short this alternate method is.
Source Link
Ryan Lundy
  • 211.3k
  • 41
  • 187
  • 216

If you don't like having to write the Deconstruct method, especially if you only need it in one place, here's how to do it as a one-liner with LINQ:

Using your original dictionary:

var dic = new Dictionary<string, int>{ ["Bob"] = 32, ["Alice"] = 17 };   

You can do it like this:

foreach (var (name, age) in dic.Select(x => (x.Key, x.Value))) { Console.WriteLine($"{name} is {age} years old."); } 

If you don't like having to write the Deconstruct method, especially if you only need it in one place, here's how to do it as a one-liner with LINQ:

var dic = new Dictionary<string, int>{ ["Bob"] = 32, ["Alice"] = 17 };   foreach (var (name, age) in dic.Select(x => (x.Key, x.Value))) { Console.WriteLine($"{name} is {age} years old."); } 

If you don't like having to write the Deconstruct method, especially if you only need it in one place, here's how to do it as a one-liner with LINQ:

Using your original dictionary:

var dic = new Dictionary<string, int>{ ["Bob"] = 32, ["Alice"] = 17 }; 

You can do it like this:

foreach (var (name, age) in dic.Select(x => (x.Key, x.Value))) { Console.WriteLine($"{name} is {age} years old."); } 
Source Link
Ryan Lundy
  • 211.3k
  • 41
  • 187
  • 216

If you don't like having to write the Deconstruct method, especially if you only need it in one place, here's how to do it as a one-liner with LINQ:

var dic = new Dictionary<string, int>{ ["Bob"] = 32, ["Alice"] = 17 }; foreach (var (name, age) in dic.Select(x => (x.Key, x.Value))) { Console.WriteLine($"{name} is {age} years old."); }