我有一个类似这样的属性的类.
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; }
}
Run Code Online (Sandbox Code Playgroud)
和我的控制器中的这个类的列表.
List<CheckList> validChecklists = _ChecklistRepo.GetAll();
var ifActionsAreSame = validChecklists .Select(t => t.ACTION_NAME).Distinct().Count();
if (ifActionsAreSame < validChecklists .Count)
{
return Ok(new {ActionsAreDuplicated= true });
}
Run Code Online (Sandbox Code Playgroud)
有时,多个项目的ACTION_NAME在列表中可以为null.此代码将null值视为重复.我需要做哪些更改才能排除ACTION_NAME字段中的空字段.
然后删除nulls Where:
int notNullDistinctActionNames = validChecklists
.Where(t => t.ACTION_NAME != null)
.Select(t => t.ACTION_NAME)
.Distinct()
.Count();
Run Code Online (Sandbox Code Playgroud)
你也可以使用Count重载:
int notNullDistinctActionNames = validChecklists
.Select(t => t.ACTION_NAME)
.Distinct()
.Count(s => s != null);
Run Code Online (Sandbox Code Playgroud)