How to validate if in a list the object in a foreach has any atribute null but not asking individually?

huangapple go评论67阅读模式
英文:

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(&quot;TABLE&quot;)
    .Filter(&quot;(U_ATRIBUTE eq &quot; + item + &quot; )&quot;)
    .GetAsync&lt;List&lt;OBJECT&gt;&gt;();

foreach (var result in results)
{
    // Here is where i&#180;m trying to validate if any atribute is null 
    // but I don&#180;t what to ask individually
    if (OBJECT.U_ATRIBUTE1 == null)
    {
        OBJECT.U_ATRIBUTE1 = &quot;0&quot;;
    }
    if (OBJECT.U_ATRIBUTE2 == null)
    {
        OBJECT.U_ATRIBUTE2 = &quot;0&quot;;
    }
    if (OBJECT.U_ATRIBUTE3  == null)
    {
        OBJECT.U_ATRIBUTE3 = &quot;0&quot;;
    }
}

答案1

得分: 2

这将返回 true,如果 obj 的任何属性为 null

英文:

Ths will return true if any property of obj is null.

var result = obj.GetType().GetProperties().Any(p =&gt; p.GetValue(obj) is null);

huangapple
  • 本文由 发表于 2023年2月8日 22:22:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75387147.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定