gpt4 book ai didi

c# - 使用 LINQ 查找通用组件

转载 作者:太空狗 更新时间:2023-10-30 00:18:29 24 4
gpt4 key购买 nike

我试图找到所有具有共同组件的订单以及共同组件列表:

组件类:

public class Component
{
public Component(string name)
{
this.Name = name;
}
public string Name { get; private set; }
}

订单类别:

internal class Order
{
public Order(string name,List<Component> components)
{
this.Name = name;
this.Components = components;
}
public string Name { get; private set; }

public List<Component>Components { get; private set; }
}

例如:

var component1 = new Component("B1");
var component2 = new Component("B2");
var component3 = new Component("B3");
var component4 = new Component("B4");

var order1 = new Order("M1", new List<Component> { component2 });
var order2 = new Order("M2", new List<Component> { component1, component2, component3, component4 });
var order3 = new Order("M3", new List<Component> { component1, component2 });

var dependents = from cmp1 in order1.Components
join cmp2 in order2.Components
on cmp1.Name equals cmp2.Name
select new
{
order1Name = order1.Name,
order2Name = order2.Name,
ComponentName = cmp1.Name
};

var result = dependents.ToList();

结果显示了正确的信息,order1order2 之间的公共(public)组件是 component2 ("B2")。

如何使用订单列表使其更通用:

    var orders = new List<Order> { order1, order2, order3 };

我想得到的结果是,对于每 2 个订单,一个共同组件列表,而不是对每个可能的对都这样做。我认为这是这样的:

var allDependents = 
runs.ForEach(order=>order.Components)
....
from cmp1 in order1.Components
join cmp2 in order2.Components
on cmp1.Name equals cmp2.Name
select new
{
order1Name = order1.Name,
order2Name = order2.Name,
ComponentName = cmp1.Name
};

附加信息:

按照下图,我们可以看到每2个订单,一个组件列表

enter image description here

最佳答案

假设所有名称都是唯一的,您可以这样做。

var results = from o1 in orders
from c1 in o1.Components
from o2 in orders.SkipWhile(o => o.Name != o1.Name)
from c2 in o2.Components
where o1.Name != o2.Name && c1.Name == c2.Name
select new
{
Order1 = o1.Name,
Order2 = o2.Name,
Component = c1.Name
};

foreach(var r in results) Console.WriteLine(r);

它产生这个输出

{ Order1 = M1, Order2 = M2, Component = B2 }

{ Order1 = M1, Order2 = M3, Component = B2 }

{ Order1 = M2, Order2 = M3, Component = B1 }

{ Order1 = M2, Order2 = M3, Component = B2 }

关于c# - 使用 LINQ 查找通用组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36034692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com