简体   繁体   English

C# 加入列表<of type>和处理 NULL/Empty 值

[英]C# Joining List<of type> and handling NULL/Empty values

I have 2 lists that I am joining.我有 2 个要加入的列表。 List 1 contains all IP's in a subnet and list 2 contains assigned IP's.列表 1 包含子网中的所有 IP,列表 2 包含分配的 IP。

Both these lists are of the same structure.这两个列表具有相同的结构。 example below (removed extra fields):下面的示例(删除了额外的字段):

int IPAddress
int AssingmentType

In list 1, "AssingmentType" will always be empty, but in list 2, both fields will be populated, but only a for assigned IP's.在列表 1 中,“AssingmentType”将始终为空,但在列表 2 中,两个字段都将被填充,但仅用于分配的 IP。 I would like to generate a full IP listing, and joing it with List 2, showingwhen an IP is assigned.我想生成一个完整的 IP 列表,并将它与列表 2 结合起来,显示何时分配了 IP。

I'm using LINQ for this and have the following so far我正在为此使用 LINQ 并且到目前为止有以下内容

            var results = from t1 in allIPinNetwork
                      join t2 in assignedIPs on t1.IPAddressText equals t2.IPAddressText into combinedIP
                      from t3 in combinedIP.DefaultIfEmpty()
                      select new IPAddress()
                      {
                          IpAddressText = t1.IpAddressText,
                          AssingmentType = t3 == null ? 0 : t3.AssingmentType,

                      };

My querie is, how best do I handle the "null" values that are for AssingmentType?我的查询是,如何最好地处理 AssingmentType 的“空”值? In this case I've set them to 0, but is there a null value I can use to leave them blank?在这种情况下,我已将它们设置为 0,但是否有一个空值可以用来将它们留空? In the full class there will also be some string fields that could be blank.在完整课程中,还会有一些字符串字段可能为空。

Happy if anyone has a better way to do this?如果有人有更好的方法来做到这一点很高兴吗?

Thanks谢谢

Both these lists are of the same structure.这两个列表具有相同的结构。

Well, that is the problem right there, they dont seem to have the structure you believe they do.好吧,这就是问题所在,它们似乎没有您认为的结构。 If the lists can have empty AssignmentType fields, then AssignmentType can not be of type int ;如果列表可以有空的AssignmentType字段,则AssignmentType不能是int类型; int must always be a value. int必须始终是一个值。

What you probably want is that both lists have the following structure:您可能想要的是两个列表都具有以下结构:

int IPAddress
int? AssignmentType

And, yes, when AssignmentType is not set, it should be null .而且,是的,当未设置AssignmentType时,它应该是null

Another option could be changing AssignmentType to an enumeration:另一种选择是将AssignmentType更改为枚举:

enum IPAssignmentType
{
     NotAssigned,
     Dynamic,
     Static,
     //whatever
}

My last option would be using -1 as unassgined value but thats just yuck if avoidable (its essentially the same as enumeration but uglier and less mantainable).我的最后一个选择是使用-1作为未分配的值,但如果可以避免,那就太糟糕了(它与枚举基本相同,但更丑陋且不易维护)。

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

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