2010-05-19 90 views
1

無法按日期排列列表。如何顯示按日期排序的數據?數據未按日期排序

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文件如下所示:

<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> 
+0

您的linq查詢甚至不會爲我運行。我得到一個構建錯誤,指出'=='不能應用於'string'和'int'類型的操作數。你運行這個代碼? – CoderDennis 2010-05-19 15:34:07

+0

我通過在where子句中使用「1」而不是1修復了構建錯誤。之後,結果如預期。 – CoderDennis 2010-05-19 15:42:53

回答

1

我不得不做出一些改動,以獲得示例代碼進行編譯和排序爲期望:

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; 

主要的事情是提供的IFormatProvider,以便系統能夠正確地解析日期。

輸出:

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

如果分離過濾的關心和數據整理成一個可測試的類,你應該能夠確認訂貨正常工作和其他地方集中你的問題的搜索。

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; 
    } 
} 

用法:

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

看看接下來的事情會是這樣,作爲@大衛-B建議,直放站是否重新排序的輸入,因爲字符串化的XmlNode值肯定會在問世如果按字符串排序,則不同順序

0
Repeater1.DataBind(); 

也許你的UI控件已限令設置爲別的東西嗎?