tags:

views:

33

answers:

1
+2  A: 

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
wo..wo.. is this i have to write in Select of Linq ? I think it is not support to declaration variables like string u did here ... please tell me where should i have to write this logic ?let say I ave select as ://code started here...from mimic in....something..select new{ ID = mimic.Attribute("ID"),NAME = mimic.Attribute("NAME"),CONTROLTYPE = mimic.Attribute("CONTROL-TYPE"), //I want to wrte here logic..... for Value as per your code
Lalit
@Lalit: It would have helped if you'd given the context beforehand... will edit.
Jon Skeet
Edited first code is running fine for me.....
Lalit