tags:

views:

622

answers:

2

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

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

+5  A: 

How about:

    var query = (from e in xml.Elements()
                 let symbol = (string)e.Attribute("symbol")
                 where symbol != null
                 orderby symbol
                 select symbol).Distinct();
Marc Gravell
Enumerable.Distinct() doesn't re-order the objects in .net 3.5, but the docs make no promise about this in the future. I would Distinct first, then apply ordering to the distinct set. http://msdn.microsoft.com/en-us/library/bb348436.aspx "method returns an unordered sequence"
David B
Fair enough - good spot. As an implementation detail, it does currently preserve order - but you are correct: the documentation does not guarantee this.
Marc Gravell
Awesome, you rock Marc.
jcollum
+2  A: 

I'd do that with lambda syntax:

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