Use IN operator in LINQ

12,021

Solution 1

// same as EXISTS
Seats.Where(s => SeatingPriorities.Any(sp => sp.CollegeId == s.CollegeId))

Also you can join seatings with seatings priorities:

// same as INNER JOIN
var prioritySeats = from s in Seats
                    join sp in SeatingPriorities
                         on s.CollegeId equals sp.CollegeId
                    select s;

NOTE: Both of queries above will not generate IN clause if you will execute them in LINQ to SQL or LINQ to Entities. IN is generated when you use Contains method of primitive types list:

var ids = SeatingPriorities.Select(sp => sp.CollegeId).ToList();
// same as IN
var prioritySeats = Seats.Where(s => ids.Contains(s.CollegeId));

Solution 2

You can use Enumerable.Contains to find out the matches like you do with in

var result = lstSeats.Where(s=>SeatingPriorities.Contains(s.CollegeId));

Solution 3

var results = source.Where(x => SeatingPriorities.Contains(x.CollegeId)).ToList();

Solution 4

Use Contains to achieve IN functionality in LINQ

Solution 5

You could use Any:

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

Since Contains only accepts an instance to compare (along with a possible IEqualityComparer<T>), which won't work if OptionPriority isn't an comparable to CollegeId (i.e. a string).

Share:
12,021
Subin Jacob
Author by

Subin Jacob

Passionate Asp.net Web Developer.

Updated on June 25, 2022

Comments

  • Subin Jacob
    Subin Jacob almost 2 years

    I have List<Candidate> Candidates, List<Seat> Seats

    The Model defined as shown below

     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; }
         }
    

    I need to filter List<Seat> from List<Seat> Seats where Seats.CollegeId IN List of CollegeID in SeatingPriorities.