创建了一个示例扩展方法,可以在表格即对象级别上验证数据。
public class Room
{
public int RoomId { get; set; }
public string Name { get; set; }
public double Temprature { get; set; }
}
List<Room> rooms = new List<Room>();
rooms.Add(new Room() { RoomId = 1, Name = "Hall", Temprature = 65 });
rooms.Add(new Room() { RoomId = 2, Name = "Kitchen", Temprature = 75 });
bool result = rooms.Expect_Column_Values_To_Be_Between("Temprature", 60, 75, .95);
public static class ValidationExtensions
{
public static bool Expect_Column_Values_To_Be_Between<T>(this List<T> items,
string columnName, double minValue, double maxValue, double mostly = 1)
{
if (mostly < 0 || mostly > 1)
throw new ArgumentOutOfRangeException(
$"Mostly value {{{mostly}}} can not be less 0 or greater than 1");
else if (mostly == 0)
return true;
if (items == null || items.Count == 0)
return false;
int itemsInRangeCount = 0;
foreach (var item in items)
{
PropertyInfo? propertyInfo = item.GetType().GetProperty(columnName);
if (propertyInfo == null)
throw new InvalidDataException($"Column not found : {columnName}");
var itemValue = Convert.ToDouble(propertyInfo.GetValue(item));
if (itemValue >= minValue && itemValue <= maxValue)
itemsInRangeCount++;
}
return (itemsInRangeCount / items.Count) >= mostly ? true : false;
}
}