我有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
,其中{{1}}位于SeatingPriorities中的CollegeID列表。
答案 0 :(得分:4)
// 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子句。使用包含原始类型的方法列表时生成IN:
var ids = SeatingPriorities.Select(sp => sp.CollegeId).ToList();
// same as IN
var prioritySeats = Seats.Where(s => ids.Contains(s.CollegeId));
答案 1 :(得分:2)
var results = source.Where(x => SeatingPriorities.Contains(x.CollegeId)).ToList();
答案 2 :(得分:2)
您可以使用Enumerable.Contains查找与in
var result = lstSeats.Where(s=>SeatingPriorities.Contains(s.CollegeId));
答案 3 :(得分:1)
使用Contains
在IN
LINQ
功能
答案 4 :(得分:1)
您可以使用Any
:
seats.Where(s => SeatingPriorities.Any(i => i.Id == s.CollegeId))
由于Contains
仅接受要比较的实例(以及可能的IEqualityComparer<T>
),如果OptionPriority
与CollegeId
无法比较,则无效即一个string
)。