2012-01-09 6 views
0

Sessions.Current.AdminProductIdがnullの場合、Where句を無視できますか?以下のコードを1行のコードに最適化したいと思います。Where句でLinqからSqlがヌルです

if (Sessions.Current.AdminProductId == null) 
    gvUsers.DataSource = DataAccess.Instance.Users; 
else 
    gvUsers.DataSource = DataAccess.Instance.Users.Where(p => p.Orders.Any(o => o.ProductId == Sessions.Current.AdminProductId)); 
+0

? –

+0

私はそれを最適化したいだけです。 – Tomas

答えて

2

あなたはちょうどこのようなwhere句内のNULLチェックを追加する必要があります。このコードの問題何

gvUsers.DataSource = DataAccess.Instance.Users.Where(p => (Sessions.Current.AdminProductId == null) || (Sessions.Current.AdminProductId != null && p.Orders.Any(o => o.ProductId == Sessions.Current.AdminProductId))); 
+0

最初のヌルチェック '(Sessions.Current.AdminProductId == null)'は必要ありません。 – Magnus