Linq to XML Noob问题 - 与属性截然不同

时间:2022-02-08 22:24:06

I'm just getting started using Linq to XML and I have a simple document with records like this:

我刚刚开始使用Linq到XML,我有一个简单的文档,其中包含以下记录:

<record date="6/27/2002" symbol="DG" price="15.00" />

I want a list of distinct symbols as strings, in order.

我想按顺序将不同符号列表作为字符串。

This gives me an unordered list of all attributes, but I'm stuck

这给了我一个所有属性的无序列表,但我被卡住了

var query =
  from e in xml.Elements()
  select e.Attribute("symbol");

How can this be modified to give me what I want?

如何修改它以给我我想要的东西?

2 个解决方案

#1


I'd do that with lambda syntax:

我用lambda语法做到这一点:

var query = xml.Elements()
               .Select(e => (string)e.Attribute("symbol"))
               .Distinct()
               .OrderBy(x=>x);

#2


How about:

    var query = (from e in xml.Elements()
                 let symbol = (string)e.Attribute("symbol")
                 where symbol != null
                 orderby symbol
                 select symbol).Distinct();

#1


I'd do that with lambda syntax:

我用lambda语法做到这一点:

var query = xml.Elements()
               .Select(e => (string)e.Attribute("symbol"))
               .Distinct()
               .OrderBy(x=>x);

#2


How about:

    var query = (from e in xml.Elements()
                 let symbol = (string)e.Attribute("symbol")
                 where symbol != null
                 orderby symbol
                 select symbol).Distinct();