2011-09-05 167 views
2

當我的數據包含數字和字母時,我應該如何使用linq對數據進行排序?LINQ:排序(將字母當作數字)

例如我現在的LINQ

Dim MyQuery = From c In XDoc.Descendants() _ 
Where c.Attribute(Y) IsNot Nothing And c.Attribute(Str) IsNot Nothing _ 
Order By Val(c.Attribute(Y).Value), Val(c.Attribute(X).Value) _ 
Select Str = c.Attribute(Str) 

返回類似下面的

13 
167 
172 
231  
44  
49 

這是不是我想它是... 輸出應該像下面的一個

13 
44  
49 
167 
172 
231  

任何想法? 謝謝你的時間

回答

3

請勿使用Value財產XAttribute - 使用explicit conversion to Integer。我認爲這應該這樣做:

Dim MyQuery = From c In XDoc.Descendants() _ 
Where c.Attribute(Y) IsNot Nothing And c.Attribute(Str) IsNot Nothing _ 
Order By CInt(c.Attribute(Y)), CInt(c.Attribute(X)) _ 
Select Str = c.Attribute(Str) 

注意,它通常是一個更好的主意,用支持的顯式轉換由XAttributeXElement使用比Int32.Parse等,作爲那麼具體XML的解析將被執行,遵循適當的標準格式。

2

將字符串轉換爲排序子句中的數字,例如,

Dim MyQuery = From c In XDoc.Descendants() _ 
Where c.Attribute(Y) IsNot Nothing And c.Attribute(Str) IsNot Nothing _ 
Order By CInt(c.Attribute(Y)), CInt(c.Attribute(X)) _ 
Select Str = c.Attribute(Str) 

注意,如果任何字符串不能轉換爲int(或者你決定什麼數字類型,你需要使用),那麼你將得到一個異常。在這種情況下,您需要做更多的事情,比如將您的序列投影到一個新的序列上,其中任何字符串表示將數字轉換爲數字,其餘字符保持原樣,結果爲字母數字排序。

+0

爲什麼在LINQ to XML已經支持直接轉換爲整數時使用'int.Parse'? –

+0

@Jon - 實際上我在那裏有'int'投射,但是我反對'.Value',我意識到它不會工作,所以我將它改爲'int.Parse()'。我沒有想到顯式轉換爲整數,感謝提醒 - 已編輯。 –

+0

我不確定C#樣式轉換爲'int'將在VB中工作,但... –