I want to find similar objects in the collection depending on the method that I implement
for example, this example class:
class myObj { public int Data1 { get; set; } public int Data2 { get; set; } public int Data3 { get; set; } }
then we implement the Similar method in the class:
public bool Similar(myObj obj) { if (obj.Data1 == this.Data1 && obj.Data2 == this.Data2) return true; return false; }
I now have this collection:
List<myObj> items = new List<myObj>(); // none similar items.Add(new myObj() { Data1 = 1, Data2 = 2, Data3 = 4 }); items.Add(new myObj() { Data1 = 2, Data2 = 3, Data3 = 18 }); items.Add(new myObj() { Data1 = 3, Data2 = 4, Data3 = 75 }); items.Add(new myObj() { Data1 = 4, Data2 = 2, Data3 = 3 }); //similar items.Add(new myObj() { Data1 = 5, Data2 = 26, Data3 = 97 }); items.Add(new myObj() { Data1 = 5, Data2 = 26, Data3 = 37 }); items.Add(new myObj() { Data1 = 10, Data2 = 45, Data3 = 47 }); items.Add(new myObj() { Data1 = 10, Data2 = 45, Data3 = 19 });
to get similar objects, I did this:
private static List<myObj> GetSimilars(List<myObj> items) { List<myObj> similars = new List<myObj>(); while (items.Count > 0) { var q = (from c in items where c.Similar(items[0]) select c).ToList(); if (q.Count > 1) { similars.AddRange(q); foreach (var obj in q) items.Remove(obj); } else items.Remove(items[0]); } return similars; }
Is there a better way to do this?