Select 数组中的每个整数

Select each int in array

我有以下 Linq 查询,它工作正常。

var results = accounts.Select(a => new
{
    Id = a.Id,
    Scores = _context.AccountAttributeStatistics.Where(at => at.AccountId == a.Id 
                             && at.LatestVersion && at.AttributeId == 39)
        .Select(at => new
        {
            Id = at.AttributeId,
            Percentile = at.Percentile,
            Percentage = at.CurrentPercentage,
        }).ToList()
 });

但是,如果不同的 AttributeId,我现在需要 运行 这个数字。我试过:

Scores = _context.AccountAttributeStatistics.Where(at => at.AccountId == a.Id 
                 && at.LatestVersion && at.AttributeId == 39 || at.AttributeId == 40 
                 || at.AttributeId == 41 || at.AttributeId == 42)

不幸的是,这似乎忽略了 at.LatestVersion 和 returns 所有分数,而不是这些属性的最新分数。

获得理想结果的最佳方式是什么?

我想过使用数组并使用 foreach 但不确定这将如何工作?

int[] attributeIds = {39, 40, 41, 42, 43};

Scores = _context.AccountAttributeStatistics.Where(at => at.AccountId == a.Id 
                 && at.LatestVersion && at.AttributeId == attributeIds.ForEach(x => x))

但是得到错误Only assignment, call, increment, decrement, and new object expressions can be used as a statement

不确定这是否是使用 linq 实现此目的的正确方法?

您需要为此添加括号。因为你已经使用了 ||或者,它会获取属性为 40、41、42 的所有记录,而不检查最新记录。

 Scores = _context.AccountAttributeStatistics.Where(at => (at.AccountId == a.Id 
             && at.LatestVersion) && (at.AttributeId == 39 || at.AttributeId == 40 
             || at.AttributeId == 41 || at.AttributeId == 42))

要么使用:

 int[] attributeIds = {39,40,41,42};
 Scores = _context.AccountAttributeStatistics.Where(at => (at.AccountId == a.Id 
             && at.LatestVersion) && attributeIds.Contains(at.AttributeId))

您可以使用 Contains()。这与 sql 中的 IN 相同。

.Where(at => at.AccountId == a.Id 
             && at.LatestVersion 
             && attributeIds.Contains(at.AttributeId))

只需添加几个括号即可解决您的问题:

Scores = _context.AccountAttributeStatistics.Where(at => at.AccountId == a.Id 
                     && at.LatestVersion && (at.AttributeId == 39 || at.AttributeId == 40 
                     || at.AttributeId == 41 || at.AttributeId == 42))

您的查询中缺少括号,因此始终包含 LatestVersion。但是我会为允许的 AttributeIds 使用一个集合并使用 Enumerable.Contains:

int[] attributeIds = {39, 40, 41, 42, 43};

....
Scores = _context.AccountAttributeStatistics
    .Where(at => at.AccountId == a.Id 
              && at.LatestVersion 
              && attributeIds.Contains(at.AttributeId))
....