gpt4 book ai didi

c# - 遍历集合项并检查每个属性的有效值

转载 作者:行者123 更新时间:2023-11-30 22:42:58 25 4
gpt4 key购买 nike

我有一个对象集合 (IQueryable)。每个对象都有各种属性,一些字符串一些日期时间,我不关心日期时间属性。我如何遍历每个对象并返回那些在一个或多个字段中可能具有空值的对象的集合

为简单起见,考虑一个 Employees 集合

每个员工可能有两个属性:名字(字符串)姓氏(字符串)

我希望有一个方法可以遍历员工集合中的所有员工,并返回缺少名字或姓氏的员工集合,即 null 或空字符串。

将 .NET 3.5 与 C# 结合使用

最佳答案

这应该让你开始:

var properties = typeof(Employee).GetProperties()
.Where(p => p.PropertyType == typeof(string));
foreach(var employee in employees) {
foreach(var property in properties) {
string value = (string)property.GetValue(employee, null);
if(String.IsNullOrWhiteSpace(value)) {
yield return employee;
break;
}
}
}

很清楚如何使用泛型对此进行概括。

更好的是只有一个实现了一些接口(interface)的具体类ISpecification<T> (明显的接口(interface)方法是 bool IsSatisfiedBy(T entity) )然后

public static IEnumerable<T> GetInvalidEntities<T>(
this IEnumerable<T> source,
ISpecification<T> specification
) {
return source.Where(x => !specification.IsSatisfiedBy(x));
}

例如:

public class EmployeeSpecification : ISpecification<Employee> {
public bool IsSatisfiedBy(Employee entity) {
Contract.Requires<ArgumentNullException>(entity != null);
return !String.IsNullOrWhiteSpace(entity.FirstName) &&
!String.IsNullOrWhiteSpace(entity.LastName);
}
}

然后你可以说:

// IEnumerable<Employee> employees;
// EmployeeSpecification specification;
var invalidEmployees = employees.GetInvalidEntitites(specification);

关于c# - 遍历集合项并检查每个属性的有效值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4149374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com