比较两个List <string>并打印重复项</string>

时间:2014-01-15 21:05:20

标签: c# linq

在比较两个List<T>对象时,我无法保留重复项。目标是将重复项添加到第三个列表,称之为list3

list1有大约5个项目,而list2有10个项目。

list3应包含以下内容:00T51234, 00T54567, 00T57894

List<string> list1 = new List<string>(){"00T51234", "00T54567", "00T57894",
                     "00T55263", "00T58965"};

List<string> list2 = new List<string>(){"00T59633", "00T52222", "00T57894", 
                     "00T52322", "00T51234", "00T54567", "00T57894", "00T57897",
                     "00T55556", "00T59563"};

List<string> list3 = new List<string>();

我尝试使用Ani's resolution,如下所示:

var lookup2 = list2.ToLookup(str => str);

var result = from str in list1
         group str by str into strGroup
         let missingCount 
              = Math.Max(0, strGroup.Count() - lookup2[strGroup.Key].Count())
         from missingStr in strGroup.Take(missingCount)
         select missingStr;

然而,这个解决方案并没有给我我正在寻找的结果。任何帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:23)

使用Enumerable.Intersect方法

List<string> duplicates = list1.Intersect(list2).ToList();

答案 1 :(得分:-1)

我想我会扔掉一些。这是上面的一些示例,但我需要更多的内部右连接。检查一下。

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class Program
    {
        public static void Main()
        {
            //Intersect
            var listA = new List<string>{"A", "B", "C", "D", "G"};
            var listB = new List<string>{"C", "C", "A", "E", "A", "F", "Q", "Q"};
            var matching = listA.Intersect(listB).ToList();
            Console.WriteLine(matching.Str());
            
            //Right Inner Join
            var query = listA.GroupJoin(listB, a => a, b => b, (a, abList) => abList.ToList());
            Console.WriteLine(query.Str());
            
            //Inner Distinct
            var innerDist = listA.Union(listB);
            Console.WriteLine(innerDist.Str());
            
            //Outter Distinct
            var flippedDupMatch = listB.Union(listA).Except(listB.Intersect(listA));
            Console.WriteLine(flippedDupMatch.Str());
        }
    }
    
    public static class Temp
    {
        public static string Str(this IEnumerable<string> str)
        {
            return str.Count() + " " + string.Join(",", str);
        }
    
        public static string Str(this List<string> str)
        {
            return str.Count() + " " + string.Join(",", str);
        }
    
        public static string Str(this IEnumerable<List<string>> str)
        {
            return str.SelectMany(x => x).ToList().Str();
        }
    }

.netFiddle