10

i'm trying to create a dictionary with a string key and a tuple value(string, bool). I'd like to make the tuple a named one, so something like:

Dictionary<string, (string, bool)> spColumnMapping = new Dictionary<string, (string, bool)>(); 

Is it possible?

Thanks

5
  • 4
    What did the compiler tell you when you tried it? Commented Aug 3, 2018 at 14:45
  • ` Dictionary<String, Tuple<String, Boolean>> dict = new Dictionary<String, Tuple<String, Boolean>>();` Commented Aug 3, 2018 at 14:47
  • 1
    var spColumnMapping = new Dictionary<string, (string name, bool theBool)>();. Works. Commented Aug 3, 2018 at 14:47
  • @KennethK. That line compiles fine, the problem is i don't know how to name the properties in the tuple. I tried doing it in the next statement but i got a warning saying the names would be ignored since they weren't defined when the tuple was created. Commented Aug 3, 2018 at 14:48
  • It is totally unclear to me what the problem is. Why didn't named tuples work in your case? Did you try just putting the names in? Commented Aug 3, 2018 at 14:50

1 Answer 1

28
void Main() { Dictionary<string, (string Foo, bool Bar)> spColumnMapping = new Dictionary<string, (string, bool)>(); spColumnMapping.Add("foo", ("Quax", false)); var x = spColumnMapping["foo"]; Console.WriteLine(x.Foo); // prints Quax Console.WriteLine(x.Bar); // prints False } 

Just name the parameters after the type.

Sign up to request clarification or add additional context in comments.

2 Comments

Yep. You can also use var and name the elements of the tuple in the new expression, like so: var spColumnMapping = new Dictionary<string, (string Foo, bool Bar)>();. I think this is a lot easier to parse mentally when you have a complex type.
I found that even with naming the tuples as above, when using TryGetValue I had to write if (spColumnMapping.TryGetValue("foo", out (string Foo, bool Bar) item)) { Console.WriteLine(${item.Foo}, {item.Bar}"); }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.