简体   繁体   English

检查对象中的任何一个是否为空并继续处理其他对象

[英]check whether any one of the object is null and proceed with other

I have a list like as this below in a class我在课堂上有一个像下面这样的列表

public class DesignHubProject{
   public List<ProjectObject<HydronicSystem>> HydronicSystems { get; set; }
}

here is the object that ProjectObject<HydronicSystem> is holding这是ProjectObject<HydronicSystem>持有的对象

public class ProjectObject<T>
{
    public Guid? Id { get; set; }
    public T OriginalObject { get; set; }
    public T ModifiedObject { get; set; }
}

Now i need to find if modified object is null i need to proceed with the original object or if it is not null use modified object it self.现在我需要找到修改后的对象是否为空我需要继续处理原始对象,或者如果它不为空使用修改后的对象它自己。

for this i am looping through the object like as below为此,我正在循环遍历对象,如下所示

    foreach(var item in designHubProject.HydronicSystems)
    {
           // here i need to check for modified object is null proceed with original object and 
            // if original object is null proceed with modified object           
    }

how can i check the object proceed with that, Could any one please suggest any idea on this that would be very grateful to me.我如何检查对象是否继续进行,请任何人对此提出任何想法,这将非常感谢我。

Thanks in advance.提前致谢。

One way is to use Extension method (usefull for code reuse):一种方法是使用Extension 方法(对于代码重用很有用):

public static class ProjectObjectExtension
{
    public static T GetObject<T>(this ProjectObject<T> projectObject)
        => projectObject.ModifiedObject ?? projectObject.OriginalObject;

    // or like @MichaelRandall suggests in his answer
    public static T GetObjectMichaelRandallWay<T>(this ProjectObject<T> projectObject)
        => EqualityComparer<T>.Default.Equals(projectObject.ModifiedObject, default) ?
            projectObject.OriginalObject :
            projectObject.ModifiedObject;
}

Then just call this method:然后只需调用此方法:

foreach(var item in designHubProject.HydronicSystems)
{
    var obj = item.GetObject();
    // rest of your code...
}

Or just call this code within your loop:或者只是在循环中调用此代码:

foreach(var item in designHubProject.HydronicSystems)
{
    var obj = item.ModifiedObject ?? item.OriginalObject;
    // rest of your code...
}

You may also use LINQ .Select() method:您也可以使用 LINQ .Select()方法:

foreach(var obj in designHubProject.HydronicSystems.Select(p => p.ModifiedObject ?? p.OriginalObject))
{
    // rest of your code...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM