Well, the simplest way is either an explicit if/else:
string value;
string controlType = (string) element.Attribute("CONTROL-TYPE");
if (controlType == "Button")
{
value = (string) element.Attribute("LINK");
}
else if (controlType == "Dropdown")
{
value = (string) element.Attribute("METHOD");
}
else
{
// What do you want to happen if it's neither of these?
}
... or use the conditional operator if you're happy with a simple default value for other control types:
string controlType = (string) element.Attribute("CONTROL-TYPE");
string value = controlType == "Button" ? (string) element.Attribute("LINK")
: controlType == "Dropdown" ? (string) element.Attribute("METHOD")
: "default value";
EDIT: Within a query expression, there are two reasonable ways to do this. First, you could use the conditional operator and a let
clause to fetch the control type just once:
var query =
from element in elements
let controlType = (string) element.Attribute("CONTROL-TYPE")
select new {
ID = (string) element.Attribute("ID"),
XYZ = controlType == "Button" ? (string) element.Attribute("LINK")
: controlType == "Dropdown" ? (string) element.Attribute("METHOD")
: "default value"
};
Alternatively - and preferrably, IMO - put this logic into a method, and then call the method from the select clause:
var query =
from element in elements
let controlType = (string) element.Attribute("CONTROL-TYPE")
select new {
ID = (string) element.Attribute("ID"),
XYZ = GetXyz(element);
};
...
private static void GetXyz(XElement element)
{
...
}
Jon Skeet
2010-08-12 06:37:52