英文:
How to validate if in a list the object in a foreach has any atribute null but not asking individually?
问题
在你的代码中,你可以使用反射来动态检查对象的属性是否为null,并在需要时设置默认值。以下是修改后的代码:
var results = await Login.Connection
.Request("TABLE")
.Filter("(U_ATRIBUTE eq " + item + " )")
.GetAsync<List<OBJECT>>();
foreach (var result in results)
{
Type objectType = typeof(OBJECT);
foreach (var property in objectType.GetProperties())
{
if (property.GetValue(result) == null)
{
if (property.PropertyType == typeof(string))
{
property.SetValue(result, "0");
}
else if (property.PropertyType == typeof(DateTime))
{
property.SetValue(result, DateTime.MinValue);
}
// Add more conditions for other data types as needed
}
}
}
这段代码会遍历对象的属性,检查它们是否为null,并根据属性的数据类型设置默认值。请根据你的实际需求和数据类型添加更多的条件。
英文:
Is there a way to validate if inside a list of objects the object that i'm currently validating in a foreach has any atribute null without asking for every atribute individually?
I´m trying to validate null atributes inside an object but they are to much and I don´t what to ask indiviualy because the default value if the request returns null will always be 0.
Sorry if there is any mistake, but english is not my native languaje.
I was trying to do this:
public class OBJECT
{
public string CODE { get; set; }
public string U_ATRIBUTE1 { get; set; }
public DateTime U_DATE { get; set; }
public string U_ATRIBUTE2 { get; set; }
public string U_ATRIBUTE3 { get; set; }
}
var results = await Login.Connection
.Request("TABLE")
.Filter("(U_ATRIBUTE eq " + item + " )")
.GetAsync<List<OBJECT>>();
foreach (var result in results)
{
// Here is where i´m trying to validate if any atribute is null
// but I don´t what to ask individually
if (OBJECT.U_ATRIBUTE1 == null)
{
OBJECT.U_ATRIBUTE1 = "0";
}
if (OBJECT.U_ATRIBUTE2 == null)
{
OBJECT.U_ATRIBUTE2 = "0";
}
if (OBJECT.U_ATRIBUTE3 == null)
{
OBJECT.U_ATRIBUTE3 = "0";
}
}
答案1
得分: 2
这将返回 true
,如果 obj
的任何属性为 null
。
英文:
Ths will return true
if any property of obj
is null
.
var result = obj.GetType().GetProperties().Any(p => p.GetValue(obj) is null);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论