如何在执行List.Sort时处理异常

kyl*_*_13 0 c# sorting

我正在对List进行排序,导致异常(FormatException).我认为问题在于其中一个用户在字段值与实际值之间存在空格字符或某些内容.如何忽略此异常并允许其他值进行排序,或者至少不破坏应用程序?

users.Sort((x, y) => DateTime.Parse(y.createdDate).CompareTo(DateTime.Parse(x.createdDate)));
Run Code Online (Sandbox Code Playgroud)

错误: mscorlib.dll中出现"System.FormatException"类型的异常,但未在用户代码中处理

附加信息:字符串未被识别为有效的DateTime.

Pat*_*man 5

您必须尝试解析,如果失败,则默认排序顺序.你需要更多的代码才能做到这一点:

users.Sort((x, y) =>
    {
        DateTime xcd, ycd;
        bool y_ok = DateTime.TryParse(y.createdDate, out ycd);
        bool x_ok = DateTime.TryParse(x.createdDate, out xcd);

        if (!x_ok && !y_ok)
        {
            return 0;
        }

        if (!x_ok)
        {
            return 1;
        }

        if (!y_ok)
        {
            return -1;
        }

        return ycd.CompareTo(xcd);
    }
Run Code Online (Sandbox Code Playgroud)