开发者

How to convert multiple SQL LEFT JOIN statement with where clause to LINQ

Is there any way to convert following SQL statement into LINQ?

select ve.EntityID
         , fin1.FinanceStat as FinanceStat_New
         , fin2.FinanceStat as FinanceStat_Old
    from ValuationEvents_PIT_New as ve
    left join FinStat_New as Fin1
    on ve.EntityID = Fin1.EntityID
    left join FinStat_Old as Fin2
    on ve.EntityID = Fin2.EntityID
    where Fin1.FinanceStat ne Fin2.FinanceStat
        and Fin2.FinanceStat is not null
        and charindex(Fin1.FinanceStat, 'abc') < 1
        and charindex(Fin1.FinanceStat, 'xyz') < 1

Here is my version of it, but I need extra pair of eyes to look at it.

var result = (from ve in valuationEventsPit
       join fsn in finStatNew on ve.EntityId equals fsn.EntityID into veFsn
       from fin1 in veFsn.DefaultIfEmpty()
       join fso in finStatOld on ve.EntityId equals fso.EntityID into veFso
       from fin2 in veFso.DefaultIfEmpty()
       select new
       {
            ve.EntityId,
            FinStatNew1 = fin1 == null ? null : fin1.FinanceStat,
           开发者_开发百科 FinStatNew2 = fin2 == null ? null : fin2.FinanceStat
       }).
       Where(x => x.FinStatNew1 != null &&
            x.FinStatNew2 != null &&
            x.FinStatNew1 != x.FinStatNew2 &&
            !(x.FinStatNew1.Contains("abc")) &&
            !(x.FinStatNew1.Contains("xyz"))).ToList();

The reason I am excluding x.FinStatNew1 == null because of the charindex(Fin1.FinanceStat, 'abc') < 1, which will always return 0 if x.FinStatNew1 is not null and 'abc' or 'xyz' is not there and if x.FinStatNew1 is null then it will return null and condition still will be false (null < 0).

Thanks a lot for your help.


I think you could reduce that query even more and rearrange some things to make it more readable. Based on the original query and these are actually LINQ to objects queries, I'd try this:

const string con1 = "abc";
const string con2 = "xyz";
var query =
    from ve in valuationEventPit
    join fsn in finStatNew on ve.EntityId equals fsn.EntityID
    join fso in finStatOld on ve.EntityId equals fso.EntityID
    let FinStatNew = fsn.FinanceStat
    let FinStatOld = fso.FinanceStat
    where FinStatNew != FinStatOld && FinStatOld != null
       && new[]{con1,con2}.All(con => !FinStatNew.Contains(con))
    select new { ve.EntityId, FinStatNew, FinStatOld };

The left join is not necessary here. Since you exclude the null values, we could just ignore them then and do the inner join.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜