我有一个C#语句,如下所示:
var errors = errorList.Select((e, i) => string.Format("Error occured #{0}: {1} (Error code = {2}).", i + 1, e.Message, e.ErrorCode)).ToArray();
当e.ErrorCode为"Error"时,我需要显示"Error occured",当e.ErrorCode为"Warning"时,需要显示"Warning occurred"。我该如何将这个条件添加到上述语句中?
谢谢。
你就不能这么做吗:
errorList.Select((e, i) => string.Format("{2} Occured #{0}: {1} (Error code = {2}).", i + 1, e.Message, e.ErrorCode)).ToArray();
我可能只是将稍微复杂一点的逻辑封装到另一个方法中,比如…
private string GetErrorCodeLogLabel(ErrorCode code)
{
if(code == ErrorCode.Error /* || .. other errors*/)
return "Error";
else if (code == ErrorCode.Warning /* || .. other warnings*/)
return "Warning";
throw new NotImplementedException(code);
}
var errors = errorList.
Select((e, i) => string.Format("{0} occured #{1}: {2} (Error code = {3}).", GetErrorCodeLogLabel(e.ErrorCode), i + 1, e.Message, e.ErrorCode)).
ToArray();
如果:(您可以修改条件),则可以使用内联
var errors = errorList.Select((e, i) => string.Format("{0} occured #{1}: {2} (Error code = {3}).",
e.ErrorCode == ErrorCode.Error ? "Error" : "Warning",
i + 1,
e.Message,
e.ErrorCode)).ToArray();