【问题标题】:Join two collections, taking the value from second collection (left outer join)加入两个集合,从第二个集合中获取值(左外连接)
【发布时间】:2014-03-05 23:48:52
【问题描述】:

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

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

和 b =

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

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

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

我试过做一个普通的左外连接,但是“三”的Value的结果总是一个空白字符串

    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();

【问题讨论】:

    标签: c# .net linq collections


    【解决方案1】:

    这应该也可以:

    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-15
      • 2017-03-11
      相关资源
      最近更新 更多