我可以在Linq Comparable中使用TryParse吗?

mar*_*zzz 16 c# linq

某种:

Documenti = Documenti
    .OrderBy(o => string.IsNullOrEmpty(o.Note))
    .ThenBy(o => Int32.TryParse(o.Note))
    .ToList();
Run Code Online (Sandbox Code Playgroud)

如果o.Note是"或不是",那将"忽略"(不是命令,放在最后)int.

我该怎么做?

Tim*_*ter 26

使用C#7或更新版本的每个人都滚动到底部,其他人都可以阅读原始答案:


是的,如果您传递正确的参数,则可以int.TryParse.两个重载都使用intas out-parameter并使用解析后的值初始化它.像这样:

int note;
Documenti = Documenti
    .OrderBy(o => string.IsNullOrEmpty(o.Note))
    .ThenBy(o => Int32.TryParse(o.Note, out note)) 
    .ToList();
Run Code Online (Sandbox Code Playgroud)

清洁方法是使用一个分析的方法int,并返回int?,如果无法解析:

public static int? TryGetInt(this string item)
{
    int i;
    bool success = int.TryParse(item, out i);
    return success ? (int?)i : (int?)null;
}
Run Code Online (Sandbox Code Playgroud)

现在您可以使用此查询(OrderByDescending因为true它比"更大" false):

Documenti = Documenti.OrderByDescending(d => d.Note.TryGetInt().HasValue).ToList();
Run Code Online (Sandbox Code Playgroud)

它比使用int.TryParseout参数中使用的局部变量更清晰.

埃里克·利珀特(Eric Lippert)评论了我的另一个答案,他给出了一个可能会受伤的例子:

C#LINQ:字符串("[1,2,3]")如何解析为数组?


更新,这已经改变了C#7.现在,您可以直接在使用out参数的位置声明变量:

Documenti = Documenti
.OrderBy(o => string.IsNullOrEmpty(o.Note))
.ThenBy(o => Int32.TryParse(o.Note, out int note)) 
.ToList();
Run Code Online (Sandbox Code Playgroud)

  • 在这种情况下,“ThenBy”是否会对 TryParse 返回的布尔成功/失败而不是双值进行排序? (4认同)

Jas*_*son 2

这不会产生预期的结果 b/cTryParse返回 abool而不是int。最简单的事情是创建一个返回int.

private int parseNote(string note) 
{   
  int num;   
  if (!Int32.TryParse(note, out num)) 
  {
    num = int.MaxValue; // or int.MinValue - however it should show up in sort   
  }

  return num; 
}
Run Code Online (Sandbox Code Playgroud)

从您的排序中调用该函数

Documenti = Documenti
    .OrderBy(o => parseNote(o.Note))
    .ToList();
Run Code Online (Sandbox Code Playgroud)

您也可以内联执行此操作,但是,我认为单独的方法可以使代码更具可读性。我确信编译器会内联它,如果它是优化的话。