简体   繁体   中英

How to check if any of the items in the generic list is null or 0

I am using the below line of code to check if any of the items in the generic lists is empty or 0

if (Region.Dept.College[index].Student.Any(
    c => c.Age=null || 
        c.Name !=null || 
        c.code!=null || 
        c.Fees!=null || 
        c.Gender!=null || 
        c.M1!=null || 
        c.grade!= null || 
        c.caste!= null || 
        c.castespecified!= null || 
        c.GradeLevel!= null || 
        c.Gradelevelspecified!= null || 
        c.FeePercent!= 0 || 
        c.FeePercentSpecified != null || 
        c.StudentRegistrationID!= null)

But even if all the items are empty it still enters the if loop, which is incorrect. please help me to correct this.

Variables are sample

You want to check whether any student has a any null property (ie c => c.Age==null || c.Name ==null ||.. ) and if so not enter the loop, so it should be:

if(!Region.Dept.College[index].Student.Any(condition))
{
  //loop code here, all students valid
}

Currently you are testing for the opposite - you are testing whether any student is valid, not if all are valid (which is equivalent to not any invalid). Also examine your null checks - depending on the data type you need different checks, ie string.IsNullOrEmpty() for strings etc.

Also I assume c.Age=null was just a typo, otherwise wouldn't compile.

Looks like you're including null ages by mistake

EDIT: Though, I might offload that validation to a method returning a boolean then just reference the method in the If . To keep it clean, make a function which takes the object as a parameter, then in that function do all this validation and return a boolean. Something like AllValuesEmpty Then, your predicate should just be the result of that function.

This is better practice because later if you want to add something to the object or change how you validate whether or not it's empty you can just change one method rather than having to search for long, complicated If conditions.

EDIT2: Also note that C# makes a distinction between NULL values any empty values. Where NULL indicates "there is no reference to anything which could be used to resolve this" and empty indicates "there is space referenced for this, but there's nothing useful stored there"

Perhaps your properties are initialized with default values in the constructor of your object. Perhaps they're empty but not NULL

c => c.Age=null

Should be

c => c.Age==null

You're basically assigning Age to null for all the students.

You have c => c.Age=null ||... —was that supposed to be c => c.Age != 0 ?

To identify which check is failing, perform them one by one with a breakpoint right after.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM