如何在Linq中选择Where

时间:2016-10-18 12:00:38

标签: c# sql linq

我是Linq的新手,我想将此sql Query转换为Linq格式。

这是SQL格式

select *
from investorwallets iw
where transactionid in 
(select investordepositid from investordeposits)
or transactionid in
(select withdrawalid from investorwithdrawals)
or transactionid in
(select paymentdistributionid from paymentdistributions)

我也看过SO这个问题,但对我来说没有运气

修改

这是我尝试过的。我使用Linqpad进行测试

from iw in  Investorwallets 
where   (
            from id in Investordeposits // I got error from here
            select id.investordepositid
        )

任何人都可以帮助我?

谢谢

2 个答案:

答案 0 :(得分:1)

最直接的是:

from iw in investorwallets 
where investordeposits.Any(iten => item.investordepositid == iw.transactionid) ||
      investorwithdrawals.Any(iten => item.withdrawalid == iw.transactionid) ||
      paymentdistributions.Any(item => item.paymentdistributionid == iw.transactionid)
select iw;

但是,您也可以将结果合并,然后执行.Contains

var ids = investorwithdrawals.Select(item => item.investordepositid)
                             .Union(investorwithdrawals.Select(item => item.withdrawalid))
                             .Union(paymentdistributions.Select(item => item.paymentdistributionid));

var result = investorwallets.Where(item => ids.Contains(item.transactionid));

答案 1 :(得分:1)

        List<investorwallet> investorwallets = GetInvestorwallets();
        List<investordeposit> investordeposits = GetInvestordeposits();
        List<investorwithdrawal> investorwithdrawals = GetInvestorwithdrawals();
        List<paymentdistribution> paymentdistributions = GetPaymentdistribution();

        List<investorwallet> newList = investorwallets.Where(x => investordeposits.Any(y=>y.investordepositid == x.transactionid)
                                        || investorwithdrawals.Any(y => y.withdrawalid == x.transactionid)
                                        || paymentdistributions.Any(y => y.paymentdistributionid == x.transactionid)).ToList();