I am having 2 lists:
List<DefectPopulation> lst_codeDefectSrc = new List<DefectPopulation>();
List<DefectPopulation> lst_codeDefectDest = new List<DefectPopulation>();
which are of type
private class DefectPopulation
{
public int ClassCode { get; set; }
public int DefectCount { get; set; }
}
Now I want to compare the two lists and find the mismatching item.
In the below if condition, it is saying mismatch is found but I want to know where it is:
List<DefectPopulation> lst_codeDefectSrc = new List<DefectPopulation>();
List<DefectPopulation> lst_codeDefectDest = new List<DefectPopulation>();
private class DefectPopulation
{
public int ClassCode { get; set; }
public int DefectCount { get; set; }
}
List<DefectPopulation> lst_diff = new List<DefectPopulation>();
if (lst_codeDefectSrc.Count == lst_codeDefectDest.Count)
{
if (lst_codeDefectSrc.Except(lst_codeDefectDest).ToList().Any()
&& lst_codeDefectDest.Except(lst_codeDefectSrc).ToList().Any())
{
status = false;
}
else
{
status = true;
}
}
Change
if (lst_codeDefectSrc.Except(lst_codeDefectDest).ToList().Any()
&& lst_codeDefectDest.Except(lst_codeDefectSrc).ToList().Any())
...
To
var inSrcNotInDest = lst_codeDefectSrc.Except(lst_codeDefectDest).ToList();
var inDestNotInSrc = lst_codeDefectDest.Except(lst_codeDefectSrc).ToList();
if (inSrcNotInDest.Any() && inDestNotInSrc.Any()){
// Use the respective list however you want
lst_diff.AddRange(inSrcNotInDest);
lst_diff.AddRange(inDestNotInSrc);
Note that the code above will use the default equality comparer, and that is reference comparison for class types. If you want value equality you should either write your own IEqualityComparer<DefectPopulation>, Implement IEquatable<DefectPopulation>, or change it to a struct, since that uses value equality per default.
This can be achieve in a following simple way.
If the intersection of two list has same number of elements as that of the lists that mean two lists are same.
You can use following code:
var commonItems = lst_codeDefectDest.Select(item => new { item.ClassCode, item.DefectCount })
.Intersect(lst_codeDefectSrc.Select(item => new { item.ClassCode, item.DefectCount }));
status = commonItems.Count() == lst_codeDefectSrc.Count;
It is very well explained here : https://dotnettutorials.net/lesson/linq-intersect-method/