I am trying to find difference between two lists and output them to a popup. But somehow i am not getting the correct difference between them using Except Methods. Please help to guide the best way to implement this
Here are the class details
public class UserDetails
{
public List<string> ManagementCenter;
public List<string> Group;
public List<string> Roles;
}
List<UserDetails> userDetailsListFirst = new List<UserDetails>();
List<UserDetails> userDetailsListSecond = new List<UserDetails>();
//This is not working
var valuesDifference = userDetailsListSecond.Except(userDetailsListFirst);
Expected Data
-------------
List A-
Management Center: JP
Application Group(s): Corporate
User Role(s): SuperRole;
List B-
Management Center: JP
Application Group(s): Corporate; Trading;Supplementary;
User Role(s): SuperRole;
Here Comparing List A with List B . and output should show missing one
Management Center: JP
Application Group(s): Trading;Supplementary;
User Role(s): SuperRole;
If this example is truly representative of what you are trying to do, you can implement the Equals override and the GetHashCode override based on the fact that you are actually looking at sets of strings. In the code below, I create a long string from the ManagementCenter, Group, and Roles lists and use that to compare equality and to create the hash code.
public class UserDetails
{
public List<string> ManagementCenter;
public List<string> Group;
public List<string> Roles;
public override bool Equals(object obj)
{
if (obj is UserDetails)
{
var otherUserDetail = obj as UserDetails;
return string.Equals(GetTestValue(this), GetTestValue(otherUserDetail));
}
else
{
return false;
}
}
static string GetTestValue(UserDetails userDetail)
{
return string.Join(";", userDetail.ManagementCenter) + "|" + string.Join(";", userDetail.Group) + "|" + string.Join(";", userDetail.Roles);
}
public override int GetHashCode()
{
return GetTestValue(this).GetHashCode();
}
}
[TestMethod]
public void TestMethod1()
{
var a1 = new UserDetails
{
ManagementCenter = new List<string> { "JP" },
Group = new List<string> { "Corporate" },
Roles = new List<string> { "SuperRole" }
};
var a2 = new UserDetails // same info, different object,
// should still be equal using
// our override of the equals method
{
ManagementCenter = new List<string> { "JP" },
Group = new List<string> { "Corporate" },
Roles = new List<string> { "SuperRole" }
};
var b = new UserDetails // different info, should not be equal
{
ManagementCenter = new List<string> { "JP" },
Group = new List<string> { "Corporate", "Trading", "Supplementary" },
Roles = new List<string> { "SuperRole" }
};
List<UserDetails> userDetailsListFirst = new List<UserDetails>();
userDetailsListFirst.Add(a1);
List<UserDetails> userDetailsListSecond = new List<UserDetails>();
userDetailsListSecond.Add(a2);
userDetailsListSecond.Add(b);
//This is now working
var valuesDifference = userDetailsListSecond.Except(userDetailsListFirst);
}