我可以使用LINQ的内一个可比的TryParse? [英] Can I use a TryParse inside Linq Comparable?
问题描述
一个排序的:
Documenti = Documenti
.OrderBy(o => string.IsNullOrEmpty(o.Note))
.ThenBy(o => Int32.TryParse(o.Note))
.ToList();
这将忽略(没有顺序,将在年底)如果o.Note为或不是 INT
。
That will "ignore" (not order, putting at the end) if o.Note is "" or not an int
.
我该怎么办呢?
推荐答案
是的,你可以,如果你传递正确的参数的 int.TryParse
。这两种重载采取 INT
为退出
-parameter并与解析里面的值初始化。所以像这样的:
Yes, you can, if you pass the correct parameters to int.TryParse
. Both overloads take the int
as out
-parameter and initialize it inside with the parsed value. So like this:
int note;
Documenti = Documenti
.OrderBy(o => string.IsNullOrEmpty(o.Note))
.ThenBy(o => Int32.TryParse(o.Note, out note))
.ToList();
在洁净办法是使用解析到 INT
的方法并返回 INT?
如果无法解析:
The clean approach is using a method that parses to int
and returns int?
if unparseable:
public static int? TryGetInt(this string item)
{
int i;
bool success = int.TryParse(item, out i);
return success ? (int?)i : (int?)null;
}
现在你可以使用这个查询( OrderByDescending
,因为真正
比大假
)
Now you can use this query(OrderByDescending
because true
is "greater" than false
):
Documenti = Documenti.OrderByDescending(d => d.Note.TryGetInt().HasValue).ToList();
这比使用在 int.TryParse
作为输出参数局部变量的清洁剂。
It's cleaner than using a local variable that is used in int.TryParse
as out parameter.
埃里克利珀评论我的另一个答案在他给当它可能会伤害一个例子:
Eric Lippert commented another answer of me where he gives an example when it might hurt:
<一个href=\"http://stackoverflow.com/questions/28988523/c-sharp-linq-how-is-string1-2-3-parsed-as-an-array#comment46233420_28988762\">C# LINQ:如何为字符串(QUOT; [1,2,3] QUOT;)解析为一个数组
这篇关于我可以使用LINQ的内一个可比的TryParse?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!