[英]Adding a condition in a LINQ statement
我有一個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'並且當e.ErrorCode為'Warning'時出現“Warning warning”時,我需要顯示“Error 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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.