Reputation: 267
I Have a list and I want to create a new one without records with duplicate values
public List<links> results = new List<links>();
public List<links> final_results = new List<links>();
public class links
{
public string url { get; set; }
public string title { get; set; }
public string description { get; set; }
public int place { get; set; }
}
results gets it's values during code. Same record may occur with unique Place property but other properties are the same. I want to ommit duplicate records which have duplicate value in the url, title and description. I wrote this code but nothing changed:
final_results = results .GroupBy(n => n.url).Select(g => g.FirstOrDefault()).ToList();
but when I bind my repeator to this new list nothing has changed. how can I ommit this duplicte value?
Upvotes: 0
Views: 4278
Reputation: 430
try using Except extension method over the Links
final_results = results.Except(--duplicate criteria--)
Upvotes: 0
Reputation: 7536
Umm, you can just do:
var results = results.DistinctBy(x=> x.url);
Or if you want to exclude by multiple fields, simpliest is this:
var results = results.DistinctBy(x=> x.url + "," + x.title + "," + x.description);
If you want to do it properly - just override Equal and GetHashCode methods of your object and put your values in HashSet.
For DistinctBy to work, you can increase your .NET version or just use MoreLINQ.
Upvotes: 0
Reputation: 45947
If you want to suppress records with equality in 3 preperties url
,title
and description
, you have to group by all of them:
final_results = results.GroupBy(n => new {n.url, n.description, n.title})
.Select(g => g.FirstOrDefault()).ToList();
Upvotes: 6