我有 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/