如果其中一个属性为NULL,则此LINQ语句崩溃。我怎样才能解决这个问题?

时间:2011-11-17 10:20:50

标签: c# .net linq

当列表中的每个gameServer都有connectedClients的集合时,我有以下linq语句,该语句效果很好。

但是当connectedClientnull时,查询会崩溃。

如何防止崩溃?

var connectedClients = (from x in gameServers
                        from y in x.ConnectedClients
                        select new
                        {
                            x.Name,
                            x.GameType,
                            ConnectedClients = new
                            {
                                y.ClientName,
                                y.ConnectedOn,
                                y.ClientIpAddressAndPort
                            }
                        }).ToList();

和..

public class GameServer
{
    public int Id;
    public ICollection<Client> ConnectedClients;
    ...
}

3 个答案:

答案 0 :(得分:8)

如果为null,则使用非空值:

var connectedClients = (
    from x in gameServers
    from y in x.ConnectedClients ?? Enumerable.Empty<Client>()
    // ...

??被称为the null-coalescing operator

答案 1 :(得分:7)

之后添加一个在第二个之前检查null的位置
var connectedClients = (from x in gameServers
                        where x.ConnectedClients != null
                        from y in x.ConnectedClients
                        select new
                        {
                            x.Name,
                            x.GameType,
                            ConnectedClients = new
                            {
                                y.ClientName,
                                y.ConnectedOn,
                                y.ClientIpAddressAndPort
                            }
                        }).ToList();

答案 2 :(得分:0)

IEnumerable<GameServer> gameServesWIthConnectedClients = from x in gameServers 
                       where x.ConnectedClients != null  
                       select x;

var connectedClients = from y in gameServesWIthConnectedClients
                       select
                           new
                               {
                                   y.Name,
                                   y.GameType,
                                   ConnectedClients =
                           new
                               {
                                   y.ConnectedClients.ClientName,
                                   y.ConnectedClients.ConnectedOn,
                                   y.ConnectedClients.ClientIpAddressAndPort
                               }
                               };
connectedClients = connectedClients.ToList();