我想根据我实现的方法在集合中找到类似的对象
例如这个示例类:
class myObj
{
public int Data1 { get; set; }
public int Data2 { get; set; }
public int Data3 { get; set; }
}
然后在类中实现类似的方法:
public bool Similar(myObj obj)
{
if (obj.Data1 == this.Data1 && obj.Data2 == this.Data2)
return true;
return false;
}
现在我有这个集合:
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 });
为了得到类似的对象,我这样做了:
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;
}
有更好的方法吗?