3

我有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>从SeatingPriorities 中的 CollegeID 列表中的List<Seat> Seats位置进行过滤。Seats.CollegeId

4

5 回答 5

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 是在使用原始类型列表的 Contains 方法时生成的:

var ids = SeatingPriorities.Select(sp => sp.CollegeId).ToList();
// same as IN
var prioritySeats = Seats.Where(s => ids.Contains(s.CollegeId));
于 2013-07-22T07:34:44.883 回答
2
var results = source.Where(x => SeatingPriorities.Contains(x.CollegeId)).ToList();
于 2013-07-22T07:34:32.237 回答
2

您可以像使用Enumerable.Contains一样查找匹配项in

var result = lstSeats.Where(s=>SeatingPriorities.Contains(s.CollegeId));
于 2013-07-22T07:34:59.607 回答
1

你可以使用Any

seats.Where(s => SeatingPriorities.Any(i => i.Id == s.CollegeId))

因为Contains只接受一个实例来比较(以及一个可能的),如果不是一个可比较的(即 a ) IEqualityComparer<T>,它将不起作用。OptionPriorityCollegeIdstring

于 2013-07-22T07:44:05.203 回答
1

用于Contains实现IN功能LINQ

于 2013-07-22T07:34:37.460 回答