How to filter dynamically using c# xelement?

c#, linq, linq-to-xml, xml

Solution

You can build query dynamically:

IEnumerable<XElement> query = apcxmlstate.Elements("thread");

foreach(var name in param)
   query = query.Where(t => (string)t.Attribute(name) == someValue);

UPDATE: I think your problem is that instead of single `someValue` variable you are trying to get different values for each attribute. But only last one is captured in lambda. You need to create local variable to store value for each lambda:

IEnumerable<XElement> singlethread = apcxmlstate.Elements("thread"); 

foreach (var name in param) {
   var value = row[name].ToString();
   singlethread = singlethread.Where(t => (string)t.Attribute(name) == value); 
}

Problem

I have done my searching and was not able to find a solution to problem that I have. I'm a bit new to c#.net. Here is my problem. I am trying to dynamically filter xelement. The number of attribute and the value of the attributes are not known, and will depend on some other routine/process. these my attribute name to filter, can be one or more attribute to filter. ``` string[] param = new string[] { "techcode", "productgroup", "photolayer" } ``` my xml file is in this form: ``` <?xml version="1.0" encoding="utf-8"?> <threads> <thread techcode="sometech" productgroup="pgroup" photolayer="player" biasewma="-0.05" /> </threads> ``` I can filter succesfully if i hardcoded something like this ``` IEnumerable<XElement> singlethread = (from el in apcxmlstate.Elements("thread") where (string)el.Attribute("techcode") == somevalue && (string)el.Attribute("productgroup") == somevalue && (string)el.Attribute("photolayer") == somevalue select el); ``` However, this is not what I want, because I will not know which attribute do I exactly want to filter. It will be generated dynamically. For example, at run time, attribute that I want to filters are techcode and productgroup only. Would any kind soul help me to provide suggestion.

Original source