当列表中的每个gameServer
都有connectedClients
的集合时,我有以下linq语句,该语句效果很好。
但是当connectedClient
为null
时,查询会崩溃。
如何防止崩溃?
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;
...
}
答案 0 :(得分:8)
如果为null,则使用非空值:
var connectedClients = (
from x in gameServers
from y in x.ConnectedClients ?? Enumerable.Empty<Client>()
// ...
答案 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();