简体   繁体   中英

how to detect if the order of two lists changed and if changed then show newly added or deleted members in c#

I want to compare two lists which has properties Id,Number,Name so i want to compare both list for example if NewList has

Id Name   Number
1  Test    1
2  Test2   2

and Oldlist has

Id  NewList Number
1    Test    1

so when we compare both list i should show text that in NewList Test2 is added or if i removed from new list then should show text that Element is removed on newline

here is my code which i have tried

StringBuilder oldPref = new StringBuilder();
StringBuilder newPref = new StringBuilder();
newList = GetPref(NewInfo).OrderBy(p => p.Number).Where(x => x.Number> 0).ToList();
OldList = GetPref(OldInfo).OrderBy(p => p.Number).Where(x => x.Number> 0).ToList();
   
foreach (var item in OldList)
{
  oldPref .Append(item.Name + Environment.NewLine);
}
foreach (var item in newList)
{
  newPref .Append(item.Name + Environment.NewLine);
}

if (!String.Equals(oldPref , newPref ))
{
  note.Append("Order Changed " + Environment.NewLine);
}
note.Append("From " + Environment.NewLine);
note.Append(oldPref);
note.Append("To " + Environment.NewLine);
note.Append(newPref);

can anybody help me with this how i do it properly thanks in advance

The easiest way is to iterate through both lists, one at a time, and see if the other list contains each element of the list that is being iterated:

    List<MyClass> oldList = ...;
    List<MyClass> newList = ...;
    
    foreach(MyClass item in oldList){
        if(newList.Contains(item) == false) {
            (insert logic for when item has been removed from oldList)
        }
    }
    
    foreach(MyClass item in newList){
        if(oldList.Contains(item) == false) {
            (insert logic for when item has been added to oldList)
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM