简体   繁体   中英

c# linq select distinct of elements with multiple attribute

I need some help to return distinct value of the attribute. I tried to google my way but not so successfull.

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 distinct tool and process attribute. I do prefer linq solution.

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

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

Appreciate any help.

I want to return distinct tool and process attribute.

It sounds like you want this 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 fluent 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 the tool for each distinct tool / process pair—given your example set { "atool", "btool", "atool", "ctool" } . However, if all you want is distinct tool values you can just do this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM