2011-11-17 37 views
2

我有以下linq声明,它很好用,当列表中的每个gameServer都有一个connectedClients的集合。如果其中一个属性为NULL,则此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; 
    ... 
} 
+2

'where y!= null'?这似乎太容易了,我一定错误地理解了你的问题。 – jv42

+0

我没有看到一个名为'connectedClient'的变量。我错过了什么吗? – Polynomial

+1

就个人而言,我会改变你的代码,当没有连接的客户端时,'ConnectedClients'是**空**而不是'null'(见例如[this](http://stackoverflow.com/questions/1969993/is-它更好地返回null或空集合))。 – AakashM

回答

7

前第二次检查空,如果为空,则使用的值不为空,而不是:

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

??被称为the null-coalescing operator

+0

现在这很棘手:) :) :)我是'''的一个粉丝.. ..一直使用它..没想到用它,那样! –

7

增加,其中来自

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(); 
+0

ahh。所以你可以在两个'from'之间放置一个'where'子句?从来不知道... –

+0

@ Pure.Krome是的,你可以做到这一点。试一试。 –

+0

+1,因为这对于有类似问题的人来说可能同样重要。 –

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(); 
相关问题