Comparing multiple items in a single list

List<Person> PList = new List<Person>(); PList.Add(new Person{ Name = "Bob", email = " Bob.b@blah.org " }); 

It basically contains duplicate lines from a file

What I'm trying to understand is how to delete everything until there is only one instance of each in the list.

My initial thought was to use a for loop to start and delete based on comparisons

 for (int i = 0; i < List.length; i++) { if (PList.position(i).name == PList.position(i++).name) if (PList.position(i).date is < PList.position(i++).date) "Then I will delete number 1" } 

However, I am wondering if there is a better or easier way to do this?

+4
source share
2 answers

try it

 PList = PList.GroupBy (x => x.Name).SelectMany (x=>x.OrderBy(y=> y.Date).Take(1)) 

I did not fulfill the request.

The idea is to group first and then order after take the first of each ordered group.

+5
source

Use the Distinct method and write the appropriate implementation of the GetHasCode and Equals methods of the Person class.

 public class Person : IEquatable<Person> { public string Name { get; set; } public string Email { get; set; } public override bool Equals(object obj) { if (obj == null) { return false; } if (obj.GetType() != GetType()) { return false; } return Equals((Person)obj); } public override int GetHashCode() { unchecked { var hash = 17; hash = hash * 23 + (Name == null ? 0 : Name.GetHashCode()); hash = hash * 23 + (Email == null ? 0 : Email.GetHashCode()); return hash; } } public bool Equals(Person other) { if (other == null) { return false; } return Name == other.Name && Email == other.Email; } } 

Then call the Enumerable.Distinct method.

0
source

All Articles