联接用于通过公共键合并保存数据的不同列表或表。
像在SQL中一样,LINQ支持以下类型的联接:
内联接,左联接,右联接,交叉联接和完全外联接。
以下示例中使用了以下两个列表:
var first = new List<string>(){ "a","b","c"}; // 剩余数据 var second = new List<string>(){ "a", "c", "d"}; // 正确的数据
var result = from f in first join s in second on f equals s select new { f, s }; var result = first.Join(second, f => f, s => s, (f, s) => new { f, s }); // Result: {"a","a"} // {"c","c"}
var leftOuterJoin = from f in first join s in second on f equals s into temp from t in temp.DefaultIfEmpty() select new { First = f, Second = t}; // 或者也可以: var leftOuterJoin = from f in first from s in second.Where(x => x == f).DefaultIfEmpty() select new { First = f, Second = s}; // Result: {"a","a"} // {"b", null} // {"c","c"} // 左外部联接方法语法 var leftOuterJoinFluentSyntax = first.GroupJoin(second, f => f, s => s, (f, s) => new { First = f, Second = s }) .SelectMany(temp => temp.Second.DefaultIfEmpty(), (f, s) => new { First = f.First, Second = s });
var rightOuterJoin = from s in second join f in first on s equals f into temp from t in temp.DefaultIfEmpty() select new {First=t,Second=s}; // Result: {"a","a"} // {"c","c"} // {null,"d"}
var CrossJoin = from f in first from s in second select new { f, s }; // Result: {"a","a"} // {"a","c"} // {"a","d"} // {"b","a"} // {"b","c"} // {"b","d"} // {"c","a"} // {"c","c"} // {"c","d"}
var fullOuterjoin = leftOuterJoin.Union(rightOuterJoin); // Result: {"a","a"} // {"b", null} // {"c","c"} // {null,"d"}
上面的示例具有简单的数据结构,因此您可以专注于从技术上理解不同的LINQ联接,但是在现实世界中,您将拥有带有需要联接的列的表。
在下面的示例中,仅使用一个类Region,实际上,您将联接两个或多个具有相同键的表(在此示例中first,second并通过common key联接ID)。
示例:考虑以下数据结构:
public class Region { public Int32 ID; public string RegionDescription; public Region(Int32 pRegionID, string pRegionDescription=null) { ID = pRegionID; RegionDescription = pRegionDescription; } }
现在准备数据(即填充数据):
// 剩余数据 var first = new List<Region>() { new Region(1), new Region(3), new Region(4) }; // 正确的数据 var second = new List<Region>() { new Region(1, "Eastern"), new Region(2, "Western"), new Region(3, "Northern"), new Region(4, "Southern") };
您可以看到在此示例first中不包含任何区域描述,因此您想从中加入它们second。然后内部联接看起来像:
// 做内部联接 var result = from f in first join s in second onf.IDequals s.ID select new { f.ID,s.RegionDescription}; // Result: {1,"Eastern"} // {3,北部} // {4,"Southern"}
此结果可以即时创建匿名对象,但这很好,但是我们已经创建了一个适当的类-因此我们可以指定它:代替 我们可以说的,它会返回相同的数据但会创建类型的对象-保持与其他对象的兼容性。select new { f.ID,s.RegionDescription};select new Region(f.ID, s.RegionDescription);Region
.NET小提琴上的实时演示