使用C#的LINQ选择具有多个属性的唯一元素

3

我希望你能帮助我返回属性的唯一值。我试过通过谷歌搜索,但并不成功。

我的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");

我的工具 = 包含不同工具的数组/列表,例如 {atool, btool, ctool}

感谢任何帮助。

1个回答

4
我希望您想要返回不同的工具和进程属性。 看起来你想要这个:
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"));

对于给定的示例集{"atool", "btool", "atool", "ctool"},这将返回每个不同工具/过程对应的工具。但是,如果您只想获取不同的工具值,可以这样做:

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

这将为您提供{"atool", "btool", "ctool"}


需要稍微修改一下,变成 var paramColl = apcxmlstate.Elements("thread") .Select(e => e.Attribute(AttName).Value) .Distinct(); - Amir Ismail

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接