Compare Two Arrays Of Different Lengths and Show Differences

前端 未结 4 609
一向
一向 2021-01-17 17:13

Problem:
I have two arrays that can possibly be different lengths. I need to iterate through both arrays and find similarities, additions, and deletions.

4条回答
  •  一生所求
    2021-01-17 17:57

    I wrote this a while back:

    Usage:

    foreach (var diff in Foo_Old.Diff(Foo_New)){
       Console.WriteLine ("{0} action performed on {1}",diff.DiffAction,diff.Value);
    }
    

    Implementation:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace LinqExtensions {
    
        enum DiffAction {
           Added,
           Removed,
           Same
        }
    
        class DiffPair {
            public T Value { get; set; }
            public DiffAction DiffAction { get; set; }
        }
    
        static class DiffExtension {
            public static IEnumerable> Diff
                     (
                         this IEnumerable original,
                         IEnumerable target 
                     ) {
    
                Dictionary results = new Dictionary();
    
                foreach (var item in original) {
                    results[item] = DiffAction.Removed;
                }
    
                foreach (var item in target) {
                    if (results.ContainsKey(item)) {
                        results[item] = DiffAction.Same;
                    } else {
                        results[item] = DiffAction.Added;
                    }
                }
                return results.Select(
                    pair => new DiffPair {
                        Value=pair.Key, 
                        DiffAction = pair.Value
                    });
            }
        }
    
    }
    

提交回复
热议问题