I want to find similar objects in a collection depending on a Method I implement
for example this sample class:
class myObj
{
public int Data1 { get; set; }
public int Data2 { get; set; }
public int Data3 { get; set; }
}
then implement Similar method in the class:
public bool Similar(myObj obj)
{
if (obj.Data1 == this.Data1 && obj.Data2 == this.Data2)
return true;
return false;
}
now I 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 the 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 that?
How about making this class, which is reusable.
You could use like this,
or pass into the constructor of a dictionary,
or in a
GroupByor like the other answer
or in other framework friendly places.