简体   繁体   English

在LINQ语句中添加条件

[英]Adding a condition in a LINQ statement

I've a C# statement as follows: 我有一个C#语句如下:

var errors =  errorList.Select((e, i) => string.Format("Error occured #{0}: {1} (Error code = {2}).", i + 1, e.Message, e.ErrorCode)).ToArray();

I need to display "Error occured" when e.ErrorCode is 'Error' and "Warning occured" when e.ErrorCode is 'Warning'. 当e.ErrorCode为'Error'并且当e.ErrorCode为'Warning'时出现“Warning warning”时,我需要显示“Error occurred”。 How do I add this condition to the above statement please? 如何将此条件添加到上述声明中?

Thanks. 谢谢。

你能不能这样做:

errorList.Select((e, i) => string.Format("{2} Occured #{0}: {1} (Error code = {2}).", i + 1, e.Message, e.ErrorCode)).ToArray();

I would probably just wrap the slightly more complex logic into another method like so.. 我可能只是将稍微复杂的逻辑包装到另一个方法中,就像这样。

        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();

You can use inline if: (you may modify the conditions) 您可以在以下情况下使用内联:(您可以修改条件)

    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM