LINQ:排序(将字母当作数字)
问题描述:
当我的数据包含数字和字母时,我应该如何使用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
任何想法? 谢谢你的时间
答
请勿使用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)
注意,它通常是一个更好的主意,用支持的显式转换由XAttribute
和XElement
使用比Int32.Parse
等,作为那么具体XML的解析将被执行,遵循适当的标准格式。
答
将字符串转换为排序子句中的数字,例如,
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
(或者你决定什么数字类型,你需要使用),那么你将得到一个异常。在这种情况下,您需要做更多的事情,比如将您的序列投影到一个新的序列上,其中任何字符串表示将数字转换为数字,其余字符保持原样,结果为字母数字排序。
为什么在LINQ to XML已经支持直接转换为整数时使用'int.Parse'? –
@Jon - 实际上我在那里有'int'投射,但是我反对'.Value',我意识到它不会工作,所以我将它改为'int.Parse()'。我没有想到显式转换为整数,感谢提醒 - 已编辑。 –
我不确定C#样式转换为'int'将在VB中工作,但... –