[英]C# is there any better way to check if more than 2 properties in an object is not null
我正在尝试检查 object 中是否有超过 2 个属性具有值,如果是则返回无效字符串
例子:
Class Student
{
string Name
string Code
string SNumber
}
考虑上面的代码示例,可以编写以下场景
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";
有没有办法可以简化?
谢谢
你实际上可以数:
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";
}
}
请注意,您可能更愿意检查
typeof(Student).GetFields() // use GetProperties() if you have them, and not fields .Select(field => field.GetValue(studentObj) as string) .Count(value => !string.IsNullOrEmpty(value))
在这里,您可以选择优化 select 语句,但作为示例,我提供此选项以供讨论:
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.