C# 要从列表中排除的Linq IN语句
我有两张桌子 合同 Id |开始日期|结束日期 不包括合同 Id |收缩 我使用以下语句获取这两组数据:C# 要从列表中排除的Linq IN语句,c#,linq,C#,Linq,我有两张桌子 合同 Id |开始日期|结束日期 不包括合同 Id |收缩 我使用以下语句获取这两组数据: var excludedContracts = from Excluded in DataContext.ExcludedTransportContracts select Excluded; // Get a collection of all
var excludedContracts = from Excluded in
DataContext.ExcludedTransportContracts
select Excluded;
// Get a collection of all live sites first
var liveContracts = from Contracts in DataContext.Contracts
where Contracts.EndDate > DateTime.Now
select Contracts;
我需要选择ExcludedContracts表中没有记录的所有合同。我已经和WHERE问题斗争了一段时间,但运气不好
如何在(1,2,3)SQL中执行类似于instatement的查询
谢谢 LINQ中in的等价项是contains,但是除了方法之外,您还应该查看LINQ
更新:如前所述,这些是IEnumerable,因此应该用于contains和for,但用于Queryable的除外我不知道您正在使用哪个查询提供程序,但如果该查询提供程序支持contains方法,您可以使用以下方法:
//get all contracts that haven't been excluded
var nonExcludedContacts = liveContracts.Where(l => !excludedContracts.Contains(l));
如果不支持该方法,则可以改用Any方法。虽然可读性不高,但可以完成任务:
//get all contracts that haven't been excluded
var nonExcludedContacts = liveContracts.Where(l => !excludedContracts.Any(e => e.ContractId == l.Id));
您可以使用
Enumerable.Contains()
函数执行此任务。尝试类似的操作。显然,如果使用“Contains”方法,应该比较类似的数据类型/对象
在contains函数中使用隐式类型变量时,编译器可能不会编译代码,但我不确定这一点
List<Contracts> excludedContracts =
(from Excluded in DataContext.ExcludedTransportContracts
select Excluded).toList();
List<Contracts> liveContracts =
(from Contracts in DataContext.Contracts
where Contracts.EndDate > DateTime.Now &&
!excludedContracts.Contains(Contracts)
select Contracts).toList();
List excludedContracts=
(从DataContext.ExcludedTransportContracts中排除)
选择Excluded).toList();
现场合同清单=
(来自DataContext.Contracts中的Contracts)
其中Contracts.EndDate>DateTime.Now&&
!excludedContracts.Contains(合同)
选择Contracts.toList();
这两个表在数据级别是否不相关?也就是说,一个合同对象有一个作为财产的排他性运输合同列表
从数据的外观来看,这可能是它们之间的关系,然后您可以执行类似于var liveContract=DataContext.Contracts.Where(c=>c.ExcludedTransportContracts.Count()==0&&c.EndDate>DateTime.Now)
我脑子里想不起来了,所以代码可能需要稍微修改。例如,var liveContracts=来自DataContext中的Contracts.Contracts,其中somelist.Contains(Contracts.EndDate)选择Contracts;这是最有效的,我没有正确设置关系,所以现在是Contracts->ExcludedContracts,正如您所说,我可以在Contracts.contractEndDate>DateTime.now&&Contracts.ExcludedTransportContracts.Count()==0作为注释,
!Contracts.ExcludedTransportContracts.Any()
将证明SQL比使用Count==0更高效。我的意思是“将提供更高效的SQL”。真遗憾,现在编辑我的评论已经太晚了,哈哈。