开发者

data is not getting ordered by date

开发者 https://www.devze.com 2022-12-31 01:20 出处:网络
Can\'t get list sorted by date. How to show data ordered by date? XDocument doc = XDocument.Load(Server.MapPath(\"file.xml\"));

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>


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.


Repeater1.DataBind(); 

Perhaps your UI control has ordering set to something else?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号