【问题标题】:How do I use LINQ to find differences between 2 lists [duplicate]如何使用 LINQ 查找 2 个列表之间的差异 [重复]
【发布时间】:2021-08-19 11:52:21
【问题描述】:

我有两组列表,我希望得到这两个列表之间的区别,但根据我的逻辑,我似乎没有得到预期的结果:

列表 A
A002
A75
B908
123456
672314
756213

列表 B
htg1
EDDIE1
EDD1E2
A002
A75
B908

预期结果
获取列表 B 中尚未在映射列表(列表 A)中维护的所有新代码 这应该给我以下所有新项目:
htg1
EDDIE1
EDDIE2

实际输出
当我应用 LINQ 逻辑进行过滤时,我得到了列表 B 中的所有项目:
htg1
EDDIE1
EDDIE2
A002
A75
B908

这是因为此连接查询返回 0 行:

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

joinItems = (from d1 in mappings
                         join d2 in references on d1.MappingId equals d2.CustCode
                         select d1.MappingId).ToList<string>();

其中映射表示 LIST A 的结果集:

List<Partner> mappings = GetMappingsAsModel();

references 代表 LIST B 的结果集:

List<CustomerCode> references = GetCustomerCodes();

为了找出我正在做的不同之处:

List<string> cuscodes = references.Select(x => x.CustCode.ToString()).ToList();
              
 var newItems = cuscodes.Except(joinItems);
            
int newCodes = cuscodes.Except(joinItems).Count();

我上面的加入查询有什么问题?

【问题讨论】:

标签: c# list linq


【解决方案1】:
    var list1 = new List<string> {
    "A002",
    "A75"  ,
    "B908"  ,
    "123456",
    "672314",
    "756213"};
    
    var list2 = new List<string> {
    "htg1"  ,
    "EDDIE1",
    "EDD1E2",
    "A002"  ,
    "A75"   ,
    "B908"    
    };
    
    
    
    foreach(var item in list2.Except(list1))
    {
    Console.WriteLine(item);
    }

【讨论】:

    【解决方案2】:

    您可以使用除 LINQ 方法来做到这一点:

            static void Main(string[] args)
        {
            var list1 = new List<string> {
                "A002",
                "A75"  ,
                "B908"  ,
                "123456",
                "672314",
                "756213"};
    
            var list2 = new List<string> {
                "htg1"  ,
                "EDDIE1",
                "EDD1E2",
                "A002"  ,
                "A75"   ,
                "B908"
            };
    
            var difference = list2.Except(list1);
    
           Console.WriteLine(string.Join(", ", difference));
    

    结果:htg1、EDDIE1、EDD1E2

    这是一个工作示例。确保您的代码列表实际填写了您作为示例提供的值。

    【讨论】:

      【解决方案3】:

      使用Except 方法产生两个序列(在您的情况下是字符串列表)的集合差异是一种很好且干净的方法。

      List<string> A = new List<string> {"A002", "A75" ,"B908" ,"123456", "672314", "756213"};
      List<string> B = new List<string> {"htg1" ,"EDDIE1", "EDD1E2", "A002","A75" ,"B908"};
      
      List<string> diffs = A.Except(B).ToList(); // ["123456", "672314", "756213"];
      
      foreach(var diff in diffs)
      {
          // work with each individual string out of diffs here
      }
      

      您可以在此处阅读有关Except 的更多信息:

      https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.except?view=net-5.0

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-01-03
        • 1970-01-01
        • 2017-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-29
        相关资源
        最近更新 更多