C#Linq Union On Attribute

时间:2010-08-30 00:14:56

标签: c# linq

我有两个linq查询,我希望在一个公共属性上进行联合:

One
{
     Id,
     Name,
     Color
}

Two
{
     Color,
     Cost
}

我希望通过加入Color来获得One和Two的结合?如果没有两个颜色对应于One,我想在输出中将Cost设置为0?我如何在LINQ中执行此操作?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

这称为 join ,而不是联盟 请参阅documentation

答案 2 :(得分:1)

您希望left outer join保持值显示在第一个列表中,但不存在于第二个列表中。