CSharp · Console
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var person1 = new Person() {id = 1, name = "Bob" };
var person2 = new Person() {id = 2, name = "Ted" };
var person3 = new Person() {id = 3, name = "Will_1" };
var person4 = new Person() {id = 4, name = "Will_2" };
person1.documents.Add(new IdentificationDocument() { number = "123" });
person2.documents.Add(new IdentificationDocument() { number = "456" });
person3.documents.Add(new IdentificationDocument() { number = "789" });
person3.documents.Add(new IdentificationDocument() { number = "147" });
person4.documents.Add(new IdentificationDocument() { number = "789" }); //duplicate
person4.documents.Add(new IdentificationDocument() { number = "147" }); //duplicate
var personList1 = new List<Person>();
personList1.Add(person1);
personList1.Add(person2);
personList1.Add(person3);
personList1.Add(person4);
//More data for performance test
for (int i = 0; i < 20000; i++)
{
var personx = new Person() { id = i, name = Guid.NewGuid().ToString() };
personx.documents.Add(new IdentificationDocument() { number = Guid.NewGuid().ToString() });
personx.documents.Add(new IdentificationDocument() { number = Guid.NewGuid().ToString() });
personList1.Add(personx);
}
var result = new List<Person>();
foreach (var person in personList1)
{
if (!result.Any(r => r.documents.SelectMany(rd => rd.number)
.Intersect(person.documents.SelectMany(pd => pd.number))
.Any()))
{
result.Add(person);
}
}
result.ForEach(r => Console.WriteLine(r.id + " " +r.name));
//Expected result:
//1 Bob
//2 Ted
//3 Will_1
//Note: Select instead SelectMany works, but is too slow when i have many elements (> 200 thousand)
}
public class Person
{
public int id { get; set; }
public string name { get; set; }
public List<IdentificationDocument> documents { get; set; }
public Person()
{
documents = new List<IdentificationDocument>();
}
}
public class IdentificationDocument
{
public string number { get; set; }
}
}