An optimized way to select items from a collection, excluding a list of specific members using Linq

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.

+3
source share
1 answer

You can create a set of state identifiers for faster searches, because the operation Contains()for the hash set is O (1) and Containsin the list is O (N):

HashSet<int> ids = new HashSet<int>(specialStateIds);

List<int> NonSpacialRollIds = Students.Where(s => !ids.Contains(s.StateId))
                                      .Select(s => s.RoleIds)
                                      .ToList();
+4

All Articles