加入两个集合,从第二个集合中获取值(左外连接)

时间:2014-03-05 23:48:52

标签: c# .net linq collections

假设我有两个List<KeyValuePair<string, string>> a和b,其中a =

"one", "N",
"two", "N",
"three", "N"

和b =

"one", "Y"
"two", "N"

我想做一个左外连接,但是如果b中有一个条目,则从Value取b的值,所以结果应为=

"one", "Y" <- this value is taken from b
"two", "N",
"three", "N"

我尝试过正常的左外连接,但{&lt; 3}的Value的结果是&#34;永远是一个空白字符串

    var res = (from l in a
              join r in b on l.Key equals r.Key into lrs
              from lr in lrs.DefaultIfEmpty()
              select new KeyValuePair<string, string>(l.Key, lr.Value)).ToArray();

1 个答案:

答案 0 :(得分:5)

这也应该有效:

var res = (from p in b.Concat(a)
           group p by p.Key into g
           select g.First()).ToArray();

或者用流利的语法:

var res = b.Concat(a).GroupBy(p => p.Key, (k, g) => g.First()).ToArray();