linq。当相等匹配时包含不匹配

时间:2018-07-21 11:10:09

标签: c# linq

以下代码没有任何结果

 var transit = _receiptRepository
            .AcceptanceDetails
            .Where(w => (w.Acceptance.PartyId == partyId || partyId == 0) &&
                         new[] { 3, 4, 5 }.Contains(w.Acceptance.StatusCode));

但使用相等运算符代替Contains符合预期

var transit = _receiptRepository
            .AcceptanceDetails
            .Where(w => (w.Acceptance.PartyId == partyId || partyId == 0) &&
                         new[] { 3, 4, 5 }.Any(x => x == w.Acceptance.StatusCode));

有人可以解释为什么这些不相等吗?

StatusCode的定义

public int StatusCode { get; set; }

以及来自存储库代码

public IEnumerable<AcceptanceDetail> AcceptanceDetails => 
    _appDbContext.AcceptanceDetail.Where(w => w.Closed == null)
                                  .Include(i => i.Acceptance);

1 个答案:

答案 0 :(得分:0)

您需要记住,表达式树是被解释的,并且与编译的行为不同。我相信表达式树无法正确转换数组。您应该先将其提取到变量中。

var statuses = new int[] { 3, 4, 5 };

var transit = _receiptRepository
        .AcceptanceDetails
        .Where(w => (w.Acceptance.PartyId == partyId || partyId == 0) &&
                     statuses .Contains(w.Acceptance.StatusCode));