如何在 C# 中获取通用列表的计数并且无需考虑计数中具有 null 或空值的项目?

How to get count of a generic list in C# and no need to consider items with null or empty values in the count?

我需要在 C# 中获取泛型列表的计数。无需考虑列表计数中的空项和 null 项。

下面是我的代码

Public class Student
{
public string Name {get;set;}
public string Age {get;set;}
}
List<student> listStudent = new List<student>();
Student studentOne=new Student();
studentOne.Name="abc";
studentOne.Age="20";
listStudent.Add(studentOne);
Student studentTwo=new Student();
studentOne.Name="def";
studentOne.Age="22";
listStudent.Add(studentTwo);
Student studentThree=new Student();
studentOne.Name=" ";
studentOne.Age=null;
listStudent.Add(studentThree);

我写了下面的代码来获取计数

listStudent.count  

它 returns 3.它是正确的,因为它在 list.But 中包含 3 行 我需要得到元素或项目的数量只有值。在我的代码中,最后一项的值为空或 empty.so 我需要计数为 2。 c# 中是否有任何内置方法可以执行相同的操作。有什么方法可以不使用循环来检查吗?

框架中没有您要查找的方法。您需要创建自己的扩展方法来实现此目的。

LINQ 可以提供帮助:

listStudent.Where(
  s => !string.IsNullOrWhiteSpace(s.Name) && s.Age != null
).Count();