var list1 = new List<(string s1, string s2)>()
{
("a","1"),
("b","2"),
("c","4")
};
var list2 = new List<(string s1, string s2)>()
{
("i","1"),
("j","2"),
("l","1"),
("m","2"),
("n","3")
};
var q = from r1 in list1
join r2 in list2
on r1.s2 equals r2.s2 into results
select results;
foreach (var item in q)
{
foreach (var item1 in item)
{
Console.WriteLine(item1);
}
Console.WriteLine("------------");
}
输出:
(i, 1)
(l, 1)
------------
(j, 2)
(m, 2)
------------
------------
由这段代码可以看出查询到的results包含3个元素,这3个元素是3个集合
第1个集合包含2个元素(i, 1),(l, 1)
第2个集合包含2个元素(j, 2),(m, 2)
第3个集合包含0个元素所以为空什么都没打印,但分割符的打印说明第3个是存在的,只是是一个空的集合
由此我们还可以看出results是由在join后的集合r2中满足条件的多个元素作为集合放进results中作为results的一个元素
再来段list1中s2有相等的代码:
var list1 = new List<(string s1, string s2)>()
{
("a","1"),
("b","2"),
("c","4"),
("e","1")
};
var list2 = new List<(string s1, string s2)>()
{
("i","1"),
("j","2"),
("l","1"),
("m","2"),
("n","3")
};
var q = from r1 in list1
join r2 in list2
on r1.s2 equals r2.s2 into result
select result;
foreach (var item in q)
{
foreach (var item1 in item)
{
Console.WriteLine(item1);
}
Console.WriteLine("------------");
}
输出:
(i, 1)
(l, 1)
------------
(j, 2)
(m, 2)
------------
------------
(i, 1)
(l, 1)
------------
——————————————————————————————
var list1 = new List<(string s1, string s2)>()
{
("a","1"),
("b","2"),
("c","4")
};
var list2 = new List<(string s1, string s2)>()
{
("i","1"),
("j","2"),
("l","1"),
("m","2"),
("n","3")
};
var q = from r1 in list1
join r2 in list2
on r1.s2 equals r2.s2 into result
select (s1:r1.s1, result:result);
foreach (var item in q)
{
Console.WriteLine(item.s1);
foreach (var item1 in item.result)
{
Console.WriteLine(item1);
}
Console.WriteLine("------------");
}
输出:
a
(i, 1)
(l, 1)
------------
b
(j, 2)
(m, 2)
------------
c
------------
这样就一目了然看出join语句后r1与result为一对多关系
再来代码:
var list1 = new List<(string s1, string s2)>()
{
("a","1"),
("b","2"),
("c","4"),
("e","1")
};
var list2 = new List<(string s1, string s2)>()
{
("i","1"),
("j","2"),
("l","1"),
("m","2"),
("n","3")
};
var q = from r1 in list1
join r2 in list2
on r1.s2 equals r2.s2 into result
select (s1:r1.s1, result:result);
foreach (var item in q)
{
Console.WriteLine(item.s1);
foreach (var item1 in item.result)
{
Console.WriteLine(item1);
}
Console.WriteLine("------------");
}
输出:
a
(i, 1)
(l, 1)
------------
b
(j, 2)
(m, 2)
------------
c
------------
e
(i, 1)
(l, 1)
------------