C # linq selects various elements with multiple attributes

I need help to return the attribute value. I tried to make Google my own way, but not so successful.

my xml is in this format:

<?xml version="1.0" encoding="utf-8"?> <threads> <thread tool="atool" process="aprocess" ewmabias="0.3" /> <thread tool="btool" process="cprocess" ewmabias="0.4" /> <thread tool="atool" process="bprocess" ewmabias="0.9" /> <thread tool="ctool" process="aprocess" ewmabias="0.2" /> </threads> 

I want to return a separate attribute of the tool and the process. I prefer linq solution.

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

.. mytool = array / list containing the distinc tool, ie {atool, btool, ctool}

Appreciate any help.

+4
source share
1 answer

I want to return a separate attribute of the tool and the process.

It looks like you want this:

 var results = from e in apcxmlstate.Elements("thread") group e by Tuple.Create(e.Attribute("process").Value, e.Attribute("tool").Value) into g select g.First().Attribute("tool").Value; 

Or in the free syntax:

 var results = apcxmlstate .Elements("thread") .GroupBy(e => Tuple.Create(e.Attribute("process").Value, e.Attribute("tool").Value)) .Select(g => g.First().Attribute("tool")); 

This will return a tool for each individual tool / process > pair specified in your example { "atool", "btool", "atool", "ctool" } . However, if all you need is different from the values โ€‹โ€‹of the tool , you can simply do this:

 var results = apcxmlstate .Select(e => e.Attribute("tool").Value) .Distinct(); 

Which will give you { "atool", "btool", "ctool" } .

+5
source

Source: https://habr.com/ru/post/1494185/


All Articles