Check for distinct value of a property in list except nulls

c#, ienumerable

Solution

Then remove the `null`s with `Where`:

int notNullDistinctActionNames = validChecklists 
    .Where(t => t.ACTION_NAME != null)
    .Select(t => t.ACTION_NAME)
    .Distinct()
    .Count();

You could also use the `Count` overload:

int notNullDistinctActionNames = validChecklists 
    .Select(t => t.ACTION_NAME)
    .Distinct()
    .Count(s => s != null);

Problem

I have a class with few properties like this. ``` public class CheckList { public int ACTION_ID { get; set; } public string ACTION_NAME { get; set; } public string ACTION_DESCRIPTION { get; set; } public bool? ACTIVE { get; set; } } ``` and List of this class in my controller. ``` List<CheckList> validChecklists = _ChecklistRepo.GetAll(); var ifActionsAreSame = validChecklists .Select(t => t.ACTION_NAME).Distinct().Count(); if (ifActionsAreSame < validChecklists .Count) { return Ok(new {ActionsAreDuplicated= true }); } ``` Sometimes the ACTION_NAME of multiple items Can be null in the list. This code treats the null value as duplicate. What changes I need to do to exclude null fields in the ACTION_NAME field.

Original source