I have a List of objects that some of them have the same Ids, so I would like to remove those elements that are duplicated.
I tried with something like this:
List<post> posts = postsFromDatabase.Distinct().ToList();
But it doesn't work!
So I wrote this method in order to avoid the duplicates:
public List<Post> PostWithOutDuplicates(List<Post> posts)
{
List<Post> postWithOutInclude = new List<Post>();
var noDupes = posts.Select(x => x.Id).Distinct();
if (noDupes.Count() < posts.Count)
{
foreach (int idPost in noDupes)
{
postWithOutInclude.Add(posts.Where(x => x.Id == idPost).First());
}
return postWithOutInclude;
}
else
{
return posts;
}
}
Any ideas of how to improve the performance??
Thanx in advance.