Tech vidhyarthi
Tech vidhyarthi

Reputation: 79

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

I need to get the count of a generic list in C#.No need to consider empty and null items in the count of list.

Below is my code

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);

I have written below code to get the count

listStudent.count  

It returns 3.it is correct as it contains 3 rows in the list.But I need to get the count of elements or items only having values. here in my code values in last item is null or empty.so I need to get count as 2. Is there any built in method in c# to do the same. is there any way to check without using loops ?

Upvotes: 0

Views: 1434

Answers (2)

Brandon Gano
Brandon Gano

Reputation: 6710

LINQ can help here:

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

Upvotes: 2

Mr.Nimelo
Mr.Nimelo

Reputation: 332

There is no method in framework that you are looking for. You need to create your own extended method to make this.

Upvotes: 0

Related Questions