Hello Fellow Developers:
I have an issue that I am sure someone out here have solved easier than what I am thinking to do. I have a list that have name and number. Name is required and could be duplicate and number could only be one, but not required.
|name|number|
|A |2 |
|A | |
|B | |
|C | |
|C | |
|D |4 |
-------------
At this moment I am performing a list.Distinct() on the name part, but it does not care about the number section.
newlist = oldlist.Distinct().ToList();
If one name that is duplicate has a number I want to keep the one with the number, which is not happening. The case of two same names and two different numbers will not happen. Any ideas?
One more thing: At this moment I don't care about sorting since distinct take care of that.
I am adding all the code for better visibility of the StackOverflow Team:
class _ClientComparer : IEqualityComparer<_Client>
{
#region IEqualityComparer<_Client> Members
public bool Equals(_Client x, _Client y)
{
if ((x.ClientNumber != 0) && (y.ClientNumber != 0))//Both clients with numbers
if (x.ClientNumber == y.ClientNumber)//both clients number the same then same clients.
return true;
else //if not the same they are different
return false;
else if (x.ClientName == y.ClientName)
return true;
else
return false;
}
public int GetHashCode(_Client obj)
{
if (obj.ClientNumber != 0)
return obj.ClientNumber.GetHashCode();
else
return obj.ClientName.GetHashCode();
}
Above the IEqualityComparer implementation and below the Distinct Call.
public List<_Client> CollectAllClients()
{
List<_Client> ClientList = new List<_Client>();
while (this.Read())
{
if (GetClientNumber() != 0)
ClientList.Add(CreateClientInstance());
else
ClientList.AddRange(CreateClientsInstance());
}
ClientList = ClientList.Distinct<_Client>(new _ClientComparer()).ToList<_Client>() ;
return ClientList;
}