This LINQ statement crashes if one of the Properties is NULL. How can I fix this?
当列表中的每个
但当
我怎样才能防止它崩溃呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
并且…
1 2 3 4 5 6 | public class GameServer { public int Id; public ICollection<Client> ConnectedClients; ... } |
如果为空,则使用非空值:
1 2 3 4 | var connectedClients = ( from x in gameServers from y in x.ConnectedClients ?? Enumerable.Empty<Client>() // ... |
添加一个在第二个开始之前检查空值的位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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(); |