user584018 user584018 - 2 months ago 8
C# Question

null check not working with ForEach Linq

I have below class,

public class DataCls
{
public string Message { get; set; }
public string Priority { get; set; }
public string Key { get; set; }
}


In below code I'm trying to generate "Key" based on values of "Message" and "Priority".

Values should be "NA", if "Message" and "Priority" are nulls.

Below code is not working and string concatenation is not happening. What's wrong here?

List<DataCls> lstData = new List<DataCls>
{
new DataCls {Message="M1", Priority=null, Key=null },
new DataCls {Message=null, Priority="P1", Key=null }
};

lstData.ForEach(a => a.Key = a.Message == null ? "NA" : a.Message + ":" + a.Priority == null ? "NA" : a.Priority);

Answer

brackets help, it would of been never null at the end because it was getting added to a static string then compared.

lstData.ForEach(
   a => a.Key = a.Message == null ? "NA" : 
        a.Message + ":" + (a.Priority == null ? "NA" : a.Priority));

but nicer like this

lstData.ForEach(
    a => a.Key = a.Message == null ? "NA" : a.Message + ":" + (a.Priority ?? "NA"));

though you may actually really intend it to be this

lstData.ForEach(a => a.Key = $"{a.Message ?? "NA"}:{a.Priority ?? "NA"}");
Comments