Find all intersecting data, not just the unique values

前端 未结 4 432
孤城傲影
孤城傲影 2021-01-11 13:52

I thought that I understood Intersect, but it turns out I was wrong.

 List list1 = new List() { 1, 2, 3, 2, 3};
 List<         


        
4条回答
  •  有刺的猬
    2021-01-11 14:17

    I don't believe this is possible with the built-in APIs. But you could use the following to get the result you're looking for.

    IEnumerable Intersect2(this IEnumerable left, IEnumerable right) {
      var map = left.ToDictionary(x => x, y => false);
      foreach ( var item in right ) {
        if (map.ContainsKey(item) ) {
          map[item] = true;
        }
      }
      foreach ( var cur in left.Concat(right) ) {
        if ( map.ContainsKey(cur) ) {
          yield return cur;
        }
      }
    }
    

提交回复
热议问题