简体   繁体   中英

C# - finding first enum in IEnumerable and casting to string

I'm working in JetBrains Rider and have ran into a warning that keeps appearing. Consider this situation:

public enum ValueEnum {
    A,B,C
}

public class Value {
    public ValueEnum ValueEnum { get; set; }
}

public class ValueWrapper {
    public IEnumerable<Value> Values { get; set; }
}

I'm trying to obtain the first enum in the list and convert it into a string. This code works fine:

var format = string.Empty;
if (alert.Values != null && alert.Values.Count > 0)
{
    var template = alert.Values.First();
    format = nameof(template.ValueEnum);
}

However I'm getting the Value assigned is not used in any execution path warning. Converting the above snippet into the following:

var format2 = string.Empty;
if (alert.Values != null)
{
    foreach (var template in alert.Values)
    {
        format2 = nameof(template.ValueEnum);
        break;
    }
}

Yields a Local variable "template" is only used to capture its name.

Is there a cleaner way to write this (using LINQ or whatnot) to be in line with c# best practices?

Assuming you actually want the string value of the enum, and not the literal string "ValueEnum", try:

alert.Values?.FirstOrDefault()?.ValueEnum.ToString() ?? string.Empty;

(Both of your approaches would have worked, had you changed nameof(template.ValueEnum) to template.ValueEnum.ToString() , but they are unnecessarily verbose).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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