Search code examples
c#.netlinq

Optimized way to select items from a Collection excluding a list of certain member using Linq


I will explain it with an example.

Suppose I have a List of Student Object, Where Student Class is:

class Student
{
    public int RollId { 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 List of RollIds from Students List, which doesn't belong to specialStates.

Currently I'm doing it as following.

List<int> NonSpacialRollIds = Students.Where(s => 
      !specialStateIds.Contains(s.StateId)).Select(s => s.RollId).ToList();

But somehow I feel, It can be optimize further using Linq, and Contains extension method of Collections can be avoided.


Solution

  • You can create set of state ids for faster search, because Contains() operation on hash set is O(1) and Contains on 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();