1

我有 3 份清单,一份给用户的付款清单,一份为同一笔付款支付的税款清单,一份为同一笔付款支付的州税清单。

问题是,每笔付款可能不存在税收或州税,因此我需要将每笔单独的付款与已支付的税款或州税相匹配,但如果其中一项或两项都不存在,则继续显示。这是有问题的特定查询,因为我现在拥有它

    var joinEverything = 
    from IP in IndividualPaymentsList
    join TD in TaxDetailsList.DefaultIfEmpty()
        on IP.UserId equals TD.UserId
        where IP.WeekEndDate == TD.WeekEndDate
    join ST in StateTaxDetailsList.DefaultIfEmpty()
        on IP.UserId equals ST.UserId
        where IP.WeekEndDate == ST.WeekEndDate
    select new 
    {
        IP.UserId,
        FedTax = TD.CheckAmount,
        StateTax = ST.CheckAmount,
        IP.CheckAmount,
    };

目前,如果在例如州税中不存在记录,我会收到“NullReferenceException:对象引用未设置为对象实例”。而不仅仅是接受 null 作为 ST.CheckAmount 中的值

4

1 回答 1

2

您正在做的DefaultIfEmpty()事情很好,但是您正在尝试检索设置为此默认值的对象的属性,例如,这TD.UserId意味着您正在调用 null.UserId。

下面是我试图让它工作的尝试——但是,我真的没有数据来测试它,所以我可能在某处弄乱了语法,或者我可能会尝试访问一个超出范围的变量——试一试,让我知道您是否遇到问题:

var joinEverything = 
    from IP in IndividualPaymentsList
    join TD in TaxDetailsList
        on IP.UserId equals TD.UserId into group1
        from g1 in group1.DefaultIfEmpty()
        where g1 == null || (IP.WeekEndDate == g1.WeekEndDate)
    join ST in StateTaxDetailsList
        on IP.UserId equals ST.UserId into group2
        from g2 in group2.DefaultIfEmpty()
        where g2 == null || IP.WeekEndDate == g2.WeekEndDate
    select new 
    {
        IP.UserId,
        FedTax = (g1 != null ? g1.CheckAmount : String.Empty), // or your default value for the type
        StateTax = (g2 != null ? g2.CheckAmount : String.Empty),
        IP.CheckAmount,
    };
于 2012-05-24T19:58:59.423 回答