Here is my class:
public class Record
{
public string PersonName {get; set;}
public string RequestID {get; set;}
}
I have a db table related to this class And I'm pulling all of it to memory at start. And I'm trying to find a relation between two people with the following algorithm :
- I pick two people(I mean records from that list, there can be multiple records of both properties)
- I list first person's
RequestID
s - For each RequestID, I list users with the same
RequestID
- For each user, I check if that user has the same
RequestID
with the second user. - If found, break and do stuff.
Here is my implementation of above algorithm :
foreach(var elem in listofFirstPerson)
{
List<Record> listofRelatedPeople = RecordList.Where(r => r. RequestID == elem.RequestID).ToList(); //I actually get distinct records from actual list and the distinct version count is about 100k
foreach(var relatedPerson in listofRelatedPeople )
{
List<Record> listofRecordsforRelatedPerson = RecordList.Where(r => r. PersonName == relatedPerson.PersonName).ToList();
for(int i = 0; i < listofRecordsforRelatedPerson.Count; i++)
{
for(int j = 0; j < listofSecondPerson.Count; j++)
{
if(listofRecordsforRelatedPerson[i].RequestID ==listofSecondPerson[j].RequestID)
//break all loops and do stuff
}
}
}
}
This algorithm works. But it is incredibly slow. As I mentioned listofRelatedPeople
is about 100k and it iterates only a few hundreds of records in about 20 seconds. How can I make this algorithm faster? Is there a faster approach? Thanks in advance.
EDIT :
In my list there are records like this :
- Name : "Jason" RequestID : "1"
- Name : "Larry" RequestID : "1"
- Name : "Kevin" RequestID : "7"
- Name : "Joshua" RequestID : "4"
- Name : "Tom" RequestID : "1"
- Name : "Tom" RequestID : "7"
- Name : "Ben" RequestID :"7"
Suppose I pick Jason and Kevin, as you see their Request IDs are not same so I need to find a relation between them. So I list users with the same RequestID and they are Larry and Tom. Then I get all records with Larry and I see that he doesn't have a record with the same RequestID with Kevin. Therefore I go to Tom, I see that Tom has the same RequestID with Kevin, so I pick Tom and it is done.