gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:38:18 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com