简体   繁体   中英

C# is there any better way to check if more than 2 properties in an object is not null

I am trying to check if more than 2 properties in a object has value and return invalid string if so

Example:

Class Student
{
  string Name
  string Code
  string SNumber
}

Considering above code example, below scenarios can be written

if(studentObj.Name != null && studentObj.Code != null) 
   return "invalid";
if(studentObj.Name != null && studentObj.SNumber != null) 
   return "invalid";
if(studentObj.Code != null && studentObj.SNumber != null) 
   return "invalid";

Is there a way this can be simplified?

Thanks

You could actually count:

class Student
{
  public string Name {get; set;}
  public string Code {get; set;}
  public string SNumber {get; set;}
}

class StudentValidator
{
  public string Validate(Student student)
  {
     int nonZeroCount = 0;
     if( student.Name is object ) nonZeroCount++;
     // in C# 9: if( student.Name is not null )
     if( student.Code is object ) nonZeroCount++;
     if( student.SNumber is object ) nonZeroCount++;
     return (nonZeroCount > 2)? "invalid" : "valid";
  }
}

Mind that you might prefer to check either with

typeof(Student).GetFields() // use GetProperties() if you have them, and not fields .Select(field => field.GetValue(studentObj) as string) .Count(value => !string.IsNullOrEmpty(value))

Here you can optionally optimize the select statement, but as an example, I offer this option for discussion:

class Program
    {
        static void Main(string[] args)
        {
            var students = new List<Student>
            {
                new Student{Name = "Mary",      Code = "1", SNumber = "001" },
                new Student{Name = "Sarah",     Code = "",  SNumber = "002" },
                new Student{Name = "",          Code = "3", SNumber = "003" },
                new Student{Name = "Katherine", Code = "4", SNumber = "004" },
                new Student{Name = "Eva",       Code = "",  SNumber = "" }
            };

            var listedProperty = from student in students
                                  select new List<string> { student.Name, student.Code, student.SNumber };

            listedProperty
                .ToList()
                .ForEach(l =>
                {
                    var nullPropertyCount = l.Count(i => string.IsNullOrWhiteSpace(i));

                    if (nullPropertyCount <= 1)
                    {
                        Console.WriteLine(string.Join(", ", l.ToArray()));
                    }
                });

                Console.ReadLine();
            }
    }

Output result to the console: 在此处输入图像描述

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