2010-08-30 80 views
0

我有,我想組織工會的共同屬性的兩個LINQ查詢:C#的LINQ聯盟在屬性

One 
{ 
    Id, 
    Name, 
    Color 
} 

Two 
{ 
    Color, 
    Cost 
} 

我希望通過虛實的顏色來獲得一個和兩個工會?如果沒有與One對應的顏色的Two,我想在輸出中將Cost設置爲0?我如何在LINQ中做到這一點?

+0

順便說一句,這是一個_property_,而不是一個屬性。 – SLaks 2010-08-30 00:29:06

回答

1

你想要一個left outer join保持值出現在第一個列表中,但不存在於第二個。

2

下面是一個使用上如何執行左外匿名類型的樣本加入:

var products = new[] { 
    new { Id = 1, Name = "Alpha", Color = "Red" }, 
    new { Id = 2, Name = "Beta", Color = "Green" }, 
    new { Id = 3, Name = "Gamma", Color = "Blue" } 
}; 
var costs = new[] { 
    new { Color = "Red", Cost = 100 }, 
    new { Color = "Blue", Cost = 200 }, 
    new { Color = "Blue", Cost = 300 } 
}; 
var query = products 
    .GroupJoin(
    costs, p => p.Color, c => c.Color, 
    (p, c) => new { p.Id, p.Name, p.Color, Costs = c.DefaultIfEmpty() } 
) 
    .SelectMany(
    gj => gj.Costs, 
    (gj, c) => new { gj.Id, gj.Name, gj.Color, Cost = c == null ? 0 : c.Cost } 
); 

查詢結果:

Id Name Color Cost 
------------------- 
1 Alpha Red 100 
2 Beta Green 0 
3 Gamma Blue 200 
3 Gamma Blue 300