c# - 在 LINQ 中使用 IN 运算符

标签 c# linq

我有 List<Candidate> Candidates, List<Seat> Seats

Model定义如下图

 public class Seat
    {

         public string CollegeId { get; set; }
         public bool isFilled { get; set; }
         public string SeatType { get; set; }
         public string RollNumber { get; set; }
    }
     public class Candidate
     {
         public string RollNumber { get; set; }
         public bool isAllotted { get; set; }
         public string Quota { get; set; }
         public int CandidateRank { get; set; }
         public List<OptionPriority> SeatingPriorities { get; set; }

     }
     public class OptionPriority
     {
         public string CollegeId { get; set; }
         public int PriorityRank { get; set; }
     }

我需要过滤 List<Seat>来自 List<Seat> Seats其中 Seats.CollegeId在 SeatingPriorities 中的 CollegeID 列表中。

最佳答案

// same as EXISTS
Seats.Where(s => SeatingPriorities.Any(sp => sp.CollegeId == s.CollegeId))

您还可以加入具有座位优先级的座位:

// same as INNER JOIN
var prioritySeats = from s in Seats
                    join sp in SeatingPriorities
                         on s.CollegeId equals sp.CollegeId
                    select s;

注意:如果您将在 LINQ to SQL 或 LINQ to Entities 中执行上述两个查询,它们将不会生成 IN 子句。当您使用原始类型列表的 Contains 方法时生成 IN:

var ids = SeatingPriorities.Select(sp => sp.CollegeId).ToList();
// same as IN
var prioritySeats = Seats.Where(s => ids.Contains(s.CollegeId));

关于c# - 在 LINQ 中使用 IN 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17782151/

相关文章:

c# - 使用 Json.Net 反序列化在某些字段上失败

c# - Listpicker 多选和 DisplayMemberPath

c# - 如何在 Linq To Sql 查询中重用 where 子句

c# - .Net Identity 中 UserManager 的奇怪行为

C# Linq List 比较和更新列表

c# - asp.net mailmessage BCC 和 CC 不起作用

c# - 我怎样才能进行内联排序?

asp.net - 如何将 ROW_NUMBER 添加到 LINQ 查询或实体?

linq - 如何从 LINQ 中的每个 "by group"获得前 3 个?

c# - 已解析上下文 (.toList()) 和未解析上下文的区别