Let’s say I have a struct that contains local environments:
public struct Environments
{
public const string Dev = "DEV";
public const string Qa1 = "SQA";
public const string Prod1 = "PROD";
public const string Prod2 = "PROD_SA";
public const string Uat = "UAT";
}
And I’d like to pull a set of XElements out of an xml doc, but only those elements that have a key that matches a value in a struct.
this.environments =(from e in
settings.Element("Settings").Element("Environments")
.Elements("Environment")
.Where( x => x.HasAttribute("name") )
join f in [struct?] on e.Attribute("name")
equals [struct value?]).ToDictionary(...)
How would I go about doing this? Do I need reflection to get the values of the constants in the struct?
First, I would probably add a static function to Environments to determine if a string “is an environment”.
Then the only question is how to fill the allEnvirons variable. If the Envrionments class does not change much, you could just manually type up the list of constants (yes, it’s repeating the constants, but only once and close by so you should remember to change both if changes need to be made). Alternatively, if Environments is changing often, you could use reflection to fill the array. Say:
Either way, your query becomes something like: