在LINQ中使用IN运算符

时间:2013-07-22 07:32:33

标签: 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,其中{{1}}位于SeatingPriorities中的CollegeID列表。

5 个答案:

答案 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)

使用ContainsIN

中实现LINQ功能

答案 4 :(得分:1)

您可以使用Any

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

由于Contains仅接受要比较的实例(以及可能的IEqualityComparer<T>),如果OptionPriorityCollegeId无法比较,则无效即一个string)。