【发布时间】:2019-05-15 16:20:38
【问题描述】:
我是 SQL 和 LINQ 的新手。我尝试了一个简单的代码来使用join...into 语法连接两个列表,但结果不是我所期望的。
public static void Main(string[] args)
{
IEnumerable<KeyValuePair<char,int>> list1 = new []{
new KeyValuePair<char,int>( 'a', 1) ,
new KeyValuePair<char,int>( 'b', 2) ,
new KeyValuePair<char,int>( 'c', 3) };
IEnumerable<KeyValuePair<char, int>> list2 = new[]{
new KeyValuePair<char,int>( 'b', 10) ,
new KeyValuePair<char,int>( 'c', 20) ,
new KeyValuePair<char,int>( 'd', 30) };
var joinQuery = from x in list1
join y in list2
on x.Key equals y.Key into joinTable
from t in joinTable
select new { element = t };
foreach (var el in joinQuery)
Console.WriteLine(el);
}
输出是:
{ element = [b, 10] }
{ element = [c, 20] }
我的预期是 joinTable 包含连接记录,例如:
{element = {[b, 2], [b, 10]}}
{element = {[c, 3], [c, 20]}}
您能解释一下... into joinTable 部分的实际作用,以及为什么我可以在最后一次选择中使用x 而我不能使用y:
var joinQuery = from x in list1
join y in list2
on x.Key equals y.Key into joinTable
from t in joinTable
select new { element = t,
first = x, // OK
second = y} // Error: The name y doesn't exist in the current context
【问题讨论】:
标签: c# linq join linq-to-sql