2

I have the following

private enum Properties
{ one, two, three }

private Dictionary <Properties, String> PropertyToString;
private Dictionary <String, Properies> StringToProperty;

How can I use LINQ to populate each of the dictionaries so that I can use the following? Is there a one line LINQ statement that would populate each?

Properties MyResult = StringToProperty["One"];
String MySResult = PropertyToString[Properties.One];

I specifically would like to use the actaull property to index in the second case.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    Not the answer you're asking for, but you may find a much better way to accomplish the end goal of what you're doing here: http://stackoverflow.com/questions/1331487/how-to-have-userfriendly-names-for-enumerations – David Mar 25 '13 at 00:23

1 Answers1

3

You can do it like this:

private Dictionary<Properties,String> PropertyToString = Enum
    .GetValues(typeof(Properties))
    .Cast<Properties>().
    .ToDictionary(v => v, v => Enum.GetName(typeof(Properties), v));

private Dictionary<String,Properties> StringToProperty = Enum
    .GetValues(typeof(Properties))
    .Cast<Properties>().
    .ToDictionary(v => Enum.GetName(typeof(Properties), v), v => v);

Note that the PropertyToString dictionary is unnecessary, because you can do this:

String MySResult = Enum.GetName(typeof(Proeprties), Properties.One);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Don't you need a `.Cast` or `.OfType` after `Enum.GetValues` in order to use LINQ? – Andrew Whitaker Mar 25 '13 at 00:29
  • @AndrewWhitaker You're right, I forgot that it returns `Array`. Thanks! – Sergey Kalinichenko Mar 25 '13 at 00:31
  • @JerKimball Absolutely, that's what it does. On the other hand, that's what the OP wants, so it should work. – Sergey Kalinichenko Mar 25 '13 at 00:42
  • 1
    The `PropertyToString` process can be further reduced down to `String MySResult = Properties.One.ToString()`, for example. – LukeH Mar 25 '13 at 01:24
  • And there's also no reason why `StringToProperty` couldn't just be something like `Properties MyResult = (Properties)Enum.Parse(typeof(Properties), "One", true);` (and wrapped-up in a helper method if that's what the OP prefers). – LukeH Mar 25 '13 at 01:28
  • 1
    @LukeH One could argue that parsing could be a bit slower than a dictionary lookup, but in general you're right. – Sergey Kalinichenko Mar 25 '13 at 01:31
  • @GregMontgomery You are welcome! If the answer solves your problem, consider accepting it by clicking the check mark to let others know that you are no longer actively looking for an improved answer. – Sergey Kalinichenko Mar 27 '13 at 01:31
  • @dasblinkenlight I have another question....see ->Another how do I use LINQ to Enumerate Dictionaries – Greg Montgomery Mar 27 '13 at 01:41