VA1267
VA1267

Reputation: 323

Joining a List with a Table in C#

I have the following Model and populated Data as follows.

public class School
{
 public int Id {get;set;}
 public string Name {get;set;}
 public string Class {get;set;}
 public bool IsActive {get;set;}
}

//After making a service I get the following data with IsActive as false initially.
List<School> schoolList = //make service call
[{1,'A','First',0} , {2,'B','Second',0}].

Next I have a MasterTable table with columns as ID,Name,Area . Eg:

1 A ABC
2 B DEF
3 H GHJ

If the data stored in Name property in schoolList matches with Name in MasterTable , then once again I need to update the IsActive property of schoolList as true .

I tried the following approach.

  1. Get all the data from MasterTable using EF Core and extract Name column and store it in a List NameFromMasterTable ;
  2. Loop schoolList.ForEach() and in the loop, check if Name is present in NameFromMasterTable and if found update , IsActive as true.

Since this approach fetches all the data from table and also looping on each and every row and updating is a expensive operation. Whats the best way to update the IsActive of schoolList to true if Name is found in MasterTable's Name column?

Upvotes: 0

Views: 234

Answers (1)

Max Wesley
Max Wesley

Reputation: 36

I think you will need at least two loops for this, but the inclusion of a HashSet<T> will prevent the O(N^2) time complexity. If you create a HashSet<string> and populate it with the Name values from MasterTable you can then use this collection as a reference when iterating schoolList to set IsActive.

The HashSet<T>.Contains() method is O(1). This is all assuming you do not care about the ID column in either of the tables, which seems to be the case.

HashSet<T> has a constructor that takes IEqualityComparer<string> if you need to be concerned with case sensitivity.

Upvotes: 1

Related Questions