在我的域名中,我有一个名为" Block"的对象。 A" Block"可以拥有" Pins"和"属性"附在它上面。
我可以创建两个组,它们给我以下结果:
Group1是:
Block:B1
Pin:P1
Pin:P2
Block:B2
Pin:P3
Pin:P4
Group2是:
Block:B1
Attribute:Att1, Value: Value1
Attribute:Att2, Value: Value2
Block:B2
Attribute:Att3, Value: Value3
Attribute:Att4, Value: Value4
现在我想把这两个结果合并成这样的结果:
结果组是:
Block:B1
Pin:P1
Pin:P2
Attribute:Att1, Value: Value1
Attribute:Att2, Value: Value2
Block:B2
Pin:P3
Pin:P4
Attribute:Att3, Value: Value3
Attribute:Att4, Value: Value4
LINQ可以实现吗?或者我是否需要取消分组结果才能在以后创建分组结果?
由于
编辑: 使用Road242解决方案,我得到了这个结果:
Pin: P1
Pin: P2
Attribute: Att1
Attribute: Att2
Pin: P3
Pin: P4
Attribute: Att3
Attribute: Att4
引脚和属性看起来很不错,但我把这些块丢失为分组键: - (
编辑: 我的查询看起来像这样:
var blockPinsQuery = from blockPinRelation in blockPinRelations
join block in blocks
on blockPinRelation.BlockId equals block.Id
join pin in pins
on blockPinRelation.PinId equals pin.Id
group pin by block
into g
select new
{
Block = g.Key,
Pins = g
};
和
var blockAttributesQuery = from blockAttributeRelation in blockAttributeRelations
join block in blocks
on blockAttributeRelation.BlockId equals block.Id
join attribute in stringAttributes
on blockAttributeRelation.AttributeId equals attribute.Id
group attribute by block
into g
select new
{
Block = g.Key,
Attributes = g
};
如您所见,相关实体之间存在关系表。但我认为这并不重要。
我的输出例程如下所示:
foreach (var group in blockPinsQuery)
{
Console.WriteLine("Block:" + group.Block.Name);
group.Pins.ToList().ForEach(x => Console.WriteLine("\t" + "Pin:" + x.Name));
}
和
foreach (var group in blockAttributesQuery)
{
Console.WriteLine("Block:" + group.Block.Name);
group.Attributes.ToList().ForEach(x => Console.WriteLine("\t" + "Attribute:" + x.Name + ", " + "Value: " + x.Value));
}
和Road242查询:
foreach (var group in joinedResults)
{
group.Pins.ToList().ForEach(p => Console.WriteLine("Pin: " + p.Name));
group.Attributes.ToList().ForEach(p => Console.WriteLine("Attribute: " + p.Name));
}
答案 0 :(得分:1)
你可以使用linq join子句:
请参阅http://msdn.microsoft.com/en-us/library/bb311040.aspx
var joinedResults =
from g1 in Group1
join g2 in Group2 on g1.Block equals g2.Block
select new { Pin = g1.Pin, Attribute = g2.Attribute };