I encountered an issue while comparing two Lists. I have two Lists of customs objects and I want to have the difference between them and then Count the numbers of results. Here is an example :
This is my custom class :
public class Contact
{
public String FirstName { get; set; }
public String LastName { get; set; }
public bool IsAdmin { get; set; }
}
And In my app when I make a difference between two List It sound like this :
List<Contact> Difference =
List1.Where(Second =>
!List2.Any(First =>
First.FirstName == Second.FirstName
&& First.LastName == Second.LastName
&& First.IsAdmin == Second.IsAdmin))
.ToList();
This method give me the results which match with the condition , so I can Group and count my results except when I have a result like that :
List<Contact> List1 = new List<Contact>
{
new Contact { Firstname = "Tom", LastName = "Smith", IsAdmin = true },
new Contact { Firstname = "Tom", LastName = "Smith", IsAdmin = true },
new Contact { Firstname = "Bob", LastName = "Smith", IsAdmin = false },
new Contact { Firstname = "Vincent", LastName = "Smith", IsAdmin = false }
};
List<Contact> List2 =new List<Contact>
{
new Contact { Firstname = "Tom", LastName = "Smith", IsAdmin = true},
new Contact { Firstname = "Bob", LastName = "Smith", IsAdmin = false}
};
When I run my method I have 1 results :
new Contact { Firstname = "Vincent", LastName = "Smith", IsAdmin = false }
because It matchs with the condition
But I want this as result :
new Contact { Firstname = "Tom", LastName = "Smith", IsAdmin = true}
new Contact { Firstname = "Vincent", LastName = "Smith", IsAdmin = false }
How could you make it possible ?
Edit : Working method :
var groups1 = List1
.GroupBy(c => new { c.Firstname, c.LastName, c.IsAdmin });
var groups2 = List2
.GroupBy(c => new { c.Firstname, c.LastName, c.IsAdmin });
var diffs = from g1 in groups1
join g2 in groups2
on g1.Key equals g2.Key into gj
from g2 in gj.DefaultIfEmpty(Enumerable.Empty<Contact>())
where g1.Count() > g2.Count()
select new { g1, g2 };
List<Contact> allDiffs = diffs
.SelectMany(x => x.g1.Take(x.g1.Count() - x.g2.Count()))
.ToList();