Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# linq select distinct of elements with multiple attribute

Tags:

c#

xml

linq

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, i.e {atool, btool, ctool}

Appreciate any help.

like image 300
Amir Ismail Avatar asked Oct 23 '25 19:10

Amir Ismail


1 Answers

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" }.

like image 177
p.s.w.g Avatar answered Oct 26 '25 09:10

p.s.w.g