Compare the difference between two list

后端 未结 3 1357
粉色の甜心
粉色の甜心 2020-12-10 02:15

I\'am trying to check the difference between two List in c#.

Example:

List FirstList = new List         


        
相关标签:
3条回答
  • 2020-12-10 03:05

    Than for this king of reuqirement you can can make use of Except function.

    List<string> newlist =  List1.Except(List2).ToList();
    

    or you can do this , so the below one create new list three which contains items that are not common in list1 and list2

    var common = List1.Intersect(List2);
    
    var list3 = List1.Except(common ).ToList();
    list3.AddRange(List2.Except(common ).ToList());
    

    the above one is help full when list1 and list2 has differenct item like

    List<string> list1= new List<string>();
    List<string> list2 = new List<string>();
    

    The FirstList is filled with the following values:

    list1.Add("COM1");
    list1.Add("COM2");
    list1.Add("COM4");
    

    The SecondList is filled with the following values:

    list2 .Add("COM1");
    list2 .Add("COM2");
    list2 .Add("COM3");
    

    by using above code list3 contains COM4 and COM3.

    0 讨论(0)
  • 2020-12-10 03:14

    Try to use Except LINQ extension method, which takes items only from the first list, that are not present in the second. Example is given below:

    List<string> ThirdList =  SecondList.Except(FirstList).ToList();
    

    You can print the result using the following code:

    Console.WriteLine(string.Join(Environment.NewLine, ThirdList));
    

    Or

    Debug.WriteLine(string.Join(Environment.NewLine, ThirdList));
    

    Note: Don't forget to include: using System.Diagnostics;

    prints:

    COM3
    
    0 讨论(0)
  • 2020-12-10 03:21

    You can use Enumerable.Intersect:

    var inBoth = FirstList.Intersect(SecondList);
    

    or to detect strings which are only in one of both lists, Enumerable.Except:

    var inFirstOnly = FirstList.Except(SecondList);
    var inSecondOnly = SecondList.Except(FirstList);
    

    To get your ThirdList:

    List<string> ThirdList = inSecondOnly.ToList();
    
    0 讨论(0)
提交回复
热议问题