我有以下工作正常的 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
并返回所有分数,而不是这些属性的最新分数。
获得理想结果的最佳方式是什么?
我想过使用数组并使用 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, 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))
关于c# - 选择数组中的每个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48924340/