Linq中关于null的WHERE子句

问题描述 投票:1回答:2

我有两个表,为简化起见,如下所示:

TheFiles

FileID | UserID
 23    |   342
 53    |   352

TheData

UserID |  DateCreated
  352  |    7/22/2014
  245  |    7/25/2014  
  589  |    7/28/2014

我想返回一个可空的int,它表示表UserID中最新的TheData(不在表TheFiles中)。因此,例如,对于此示例数据,返回值将为589,因为它是TheData中的最新条目,而不在TheFiles表中。

当没有数据时,我在where上遇到了麻烦。这就是我所拥有的:

var TheNullableInt = (from d in MyDC.TheData
                      where d.UserID doesn't exist in MyDC.TheFiles
                      orderby d.DateCreated descending
                      select d.UserID).FirstOrDefault();

我正在使用linq-to-SQL。我该如何处理where子句?

c# linq linq-to-sql
2个回答
1
投票
from d in MyDC.TheData
     where  !MyDC.TheFiles.Any(tf=>tf.UserID == d.UserID)

或执行join

from d in MyDC.TheData
join tf in MyDC.TheFiles on tf.UserID equals tf.UserID into j
from x in j.DefaultIfEmpty()
where x == null
select.....

1
投票
var lastest = MyDC.TheData.Where(d => !MyDC.TheFiles.Any(f => f.UserID == d.UserID))
                          .OrderByDescending()
                          .FirstOrDefault();

或者,如果您really想使用LINQ

var latest = (from d in MyDC.TheData
              where !MyDC.TheFiles.Any(f => f.UserID == d.UserID)
              orderby d.DateCreated descending
              select d
             ).FirstOrDefault();
© www.soinside.com 2019 - 2024. All rights reserved.