Below code provides the complete solution to get distinct objects from list of objects.
using System.Collections.Generic;
public class Team
{
public string Name {get;set;}
public int Score {get;set;}
}
//Create some dummy data with duplicates
public List<Team> lstTeam = new List<Team>{
new Team{Name="Brazil", Score=1},
new Team{Name="Man U", Score=1},
new Team{Name="Man U", Score=1},
new Team{Name="Brazil", Score=2},
new Team{Name="Man U", Score=2},
new Team{Name="Brazil", Score=2}
};
//This is where we use equality comparer implementation to find unique records
List<Team> lstDistictTeams = lstTeam.Distinct<Team>(new DistinctComparer()).ToList();
foreach(Team t in lstDistictTeams) // Output Distinct Objects
{
Console.WriteLine("Team {0} has Score {1}",t.Name,t.Score);
}
//This class provides a way to compare two objects are equal or not
public class DistinctComparer : IEqualityComparer<Team>
{
public bool Equals(Team x, Team y)
{
return (x.Name == y.Name && x.Score == y.Score); // Here you compare properties for equality
}
public int GetHashCode(Team obj)
{
return (obj.Name.GetHashCode() + obj.score.GetHashCode());
}
}
No comments:
Post a Comment