I will explain this with an example.
Suppose I have a list of student objects, where the class of students,
class Student
{
public int RollNo {get; set;}
public string Name { get; set; }
public int StateId { get; set; }
}
and a list containing special StateIds
List<int> specialStateIds;
Now I want to extract the List of RollIds from a list of students that does not belong to special states. I am currently doing this as follows.
List<int> NonSpacialRollIds = Students.Where(s =>
!specialStateIds.Contains(s.StateId)).Select(s => s.RoleIds).ToList();
But for some reason I feel that it can be optimized using the Linq and Contains method of the Collections extension.
source
share