Reputation: 4864
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.
Upvotes: 3
Views: 12038
Reputation: 236208
// 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));
Upvotes: 4
Reputation: 45083
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
).
Upvotes: 1
Reputation: 148110
You can use Enumerable.Contains to find out the matches like you do with in
var result = lstSeats.Where(s=>SeatingPriorities.Contains(s.CollegeId));
Upvotes: 2
Reputation: 125620
var results = source.Where(x => SeatingPriorities.Contains(x.CollegeId)).ToList();
Upvotes: 2