c# - 选择数组中的每个整数

标签 c# linq linq-to-entities

我有以下工作正常的 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/

相关文章:

c# - LINQ to Entities 无法识别方法 'System.Web.Security.MembershipUser GetUser()Method'

c# - 将 WP8 升级到 Silverlight WP8.1,程序集问题

c# - 构造函数未被调用

C#/LINQ : Concatenating strings

entity-framework - 以实体属性作为参数的 EF 自定义选择

.net - 如何从 Linq 2 SQL 迁移到 Linq 2 实体?

c# - 为什么在不影响其值的情况下允许在任何成员变量(即调用函数/属性)之前使用 '@'?

c# - 使用自定义 CommandTimeout 的 WebMatrix Database.Query

c# - 设置 DataLoadOptions 时,LINQ 返回错误的项目数

c# - LINQ 的三元运算符问题