假设我们有一个容器列表,每个容器都是一个对象。 在每个容器中都有一些对象。
我们如何找到所有重复的对象,这些对象在两个或多个容器中共享?
每个容器都有一个ID,Name,对象列表作为属性。 每个对象都有一个ID和名称。
请看图片:
结果应该是:
-------------
Object1.Name
Object2.Name
Object3.Name
-------------
我使用了一些不正确的代码
public class Container
{
public string ID;
public string Name;
public string Top, Left, Right, Bottom;
public List<ObjectX> Objects = new List<ObjectX>();
}
public class ObjectX
{
public string ID;
public string Name;
public string Top, Left, Right, Bottom;
}
List<Container> AllBoundaries = new List<Container>();
List<ObjectX> all_components = new List<ObjectX>();
Container b1 = new Container();
b1.Name = "Boundary1";
b1.ID = "1";
AllBoundaries.Add(b1);
Container b2 = new Container();
b2.Name = "Boundary2";
b2.ID = "2";
AllBoundaries.Add(b2);
Container b3 = new Container();
b3.Name = "Boundary3";
b3.ID = "3";
AllBoundaries.Add(b3);
//----------------------------------------------------------------------------------------
ObjectX c1 = new ObjectX();
c1.ID = "1";
c1.Name = "c1";
b1.Objects.Add(c1);
ObjectX c2 = new ObjectX();
c2.ID = "2";
c2.Name = "c2";
b1.Objects.Add(c2);
ObjectX c3 = new ObjectX();
c3.ID = "3";
c3.Name = "c3";
b1.Objects.Add(c3);
ObjectX c22 = new ObjectX();
c22.ID = "2";
c2.Name = "c2";
b2.Objects.Add(c2);
foreach (Container bx1 in AllBoundaries )
{
foreach (Container bx2 in AllBoundaries)
{
for (int i = 1; i < bx2.Objects.Count; i++)
if (bx1.ID != bx2.ID)
{
List<ObjectX> query = bx1.Objects.FindAll(bx => bx.Name == bx2.Objects[i].Name);
Console.WriteLine(bx2.Objects[i].Name + " Distributed");
bx2.Objects.Remove(bx2.Objects[i]);
}
}
}
但是这给了我1到9的所有对象,这是不正确的。
答案 0 :(得分:0)
假设您有一个容器集合,您可以执行以下操作:
var item = from c in containers
from o in c.Objects
group c.ContainerName by o into g
where g.Distinct().Count() > 1
select g.Key;