首页 > 解决方案 > 在 Where 子句中使用 Or 和 Select 将所有条目与 int 和 lambda 表达式进行比较

问题描述

我必须使用这种方法GetByNameOrAwardYearOrderedByAwardYearDesc来显示所有具有正确姓名的获奖者或那一年内的所有获奖者,我已经非常接近了,但我遇到了一个错误

operator == 不能应用于类型为IEnumerable<int>and的操作数int

我理解错误,但我不知道如何正确解决它。我一直在尝试很多东西并在网上搜索,但我找不到任何这样的例子。

public ICollection<Laureate> GetByNameOrAwardYearOrderedByAwardYearDesc(string name, int year)
{
    List<Laureate> laureatesList = _dbContext.Laureates
                                             .Include(p => p.Prizes)
                                             .Where(p => p.Name == name || p.Prizes.Select(ay => ay.AwardYear) == year)
                                             // .Where(p => p.Name == name || p.Prizes.Select(ay => ay.AwardYear == year)
                                             // .Where(p => p.Name == name || p.Prizes.AwardYear == year)
                                            .Select(p => new Laureate
                                                         {
                                                             Id = p.Id,
                                                             Name = p.Name,
                                                             FamilyName = p.FamilyName,
                                                             BirthDate = p.BirthDate,
                                                             Prizes = p.Prizes
                                                         }) 
                                            .ToList();

    return laureatesList; 
}

public class Laureate
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string FamilyName { get; set; }
    public DateTime? BirthDate { get; set; }
    public List<Prize> Prizes { get; set; }
}

public class Prize
{
    public int Id { get; set; }
    public int AwardYear { get; set; }
    public int CategoryId { get; set; }
    public virtual Category Category { get; set; }
    public DateTime? DateAwarded { get; set; }
    public PrizeStatus Status { get; set; }
    public String Motivation { get; set; }
    public decimal Amount { get; set; }
    public int LaureateId { get; set; }
    public virtual Laureate Owner { get; set; }
}

标签: c#linqselectlambdawhere-clause

解决方案


您可以尝试Where通过添加Any方法来更新您的条款

.Where(p => p.Name == name || p.Prizes.Any(ay => ay.AwardYear == year))
.Select(...)
//rest of code

既然你想找

当年所有获奖者

Any方法检查序列的任何元素是否满足条件,在您的情况下,您正在检查给定的任何奖品是否Laureate在给定年份授予


推荐阅读