c#linq选择具有多个属性的元素中的distinct



我需要一些帮助来返回属性的不同值。我试着用谷歌搜索,但没有那么成功。

我的xml格式是:

<?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>

我想返回不同的工具和过程属性。我更喜欢linq溶液。

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

mytool=包含不同工具的数组/列表,即{atool,btool,ctool}

感谢您的帮助。

我想返回不同的工具和过程属性。

听起来你想要这个:

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;

或者用流利的语法:

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

这将为每个不同的tool/process对返回tool—给定您的示例集CCD_ 4。然而,如果你想要的只是不同的tool值,你可以这样做:

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

这将给你{ "atool", "btool", "ctool" }

最新更新