views:

49

answers:

2

Can't get list sorted by date. How to show data ordered by date?

XDocument doc = XDocument.Load(Server.MapPath("file.xml"));
IEnumerable<XElement> items = from item in doc.Descendants("item")
                                      orderby Convert.ToDateTime(item.Attribute("lastChanges").Value) descending
                                      where item.Attribute("x").Value == 1
                                      select item;

        Repeater1.DataSource = items;
        Repeater1.DataBind();

Xml file looks like this:

<root>
  <items>
    <item id="1" lastChanges="15-05-2010" x="0" />
    <item id="2" lastChanges="16-05-2010" x="1" />
    <item id="3" lastChanges="17-05-2010" x="1" />
  </items>
</root>
A: 
Repeater1.DataBind(); 

Perhaps your UI control has ordering set to something else?

David B
A: 

I had to make a couple of changes to get the sample code to compile and sort as desired:

var formatter = new DateTimeFormatInfo
    {
        ShortDatePattern = "dd/MM/yyyy"
    };
var items = from item in doc.Descendants("item")
            orderby Convert.ToDateTime(item.Attribute("lastChanges").Value, formatter) descending
            where item.Attribute("x").Value == "1"
            select item;

The main thing was to provide an IFormatProvider so that the system could correctly parse the dates.

Output:

<item id="3" lastChanges="17-05-2010" x="1" />
<item id="2" lastChanges="16-05-2010" x="1" />

If you separate the concern of filtering and ordering the data into a testable class you should be able verify that ordering works correctly and focus your problem search elsewhere.

public class DataSource
{
    private readonly XDocument _doc;

    public DataSource(XDocument doc)
    {
        _doc = doc;
    }

    public IEnumerable<XElement> GetSortedFilteredElements()
    {
        var formatter = new DateTimeFormatInfo
            {
                ShortDatePattern = "dd/MM/yyyy"
            };
        var items = from item in _doc.Descendants("item")
                    orderby Convert.ToDateTime(item.Attribute("lastChanges").Value, formatter) descending
                    where item.Attribute("x").Value == "1"
                    select item;
        return items;
    }
}

usage:

Repeater1.DataSource =
  new DataSource(XDocument.Load(Server.MapPath("file.xml")))
    .GetSortedFilteredElements();

The next thing to look at would be, as @david-b suggested, whether the Repeater is reordering the inputs because the stringified XmlNode values would definitely come out in a different order if sorted as strings.

Handcraftsman