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

本文关键字:崩溃 语句 问题 解决 LINQ 这个 一个 NULL 属性 如果 | 更新日期: 2023-09-27 18:15:03

我有以下linq语句,当列表中的每个gameServer都有connectedClients的集合时,它工作得很好。

但当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;
    ...
}

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

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

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

??称为空合并操作符

添加一个where来检查是否为空
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();
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();