1

I have listA, listB. listA is subset of listB. For example, 1 element is deleted and 2 elements are added to listB. Then if listA contains the element that was deleted from listB, delete it from listA. Also, listA should add the newly added elements.

At present I am using foreach{ if(list.contains) } two times. Once to add and once to delete. This will be of O(2n), which is ok.

But is there a best way to do this mostly with O(n) in LINQ/any other way?.

To be more clear:
Actually I have a list of custom class.
From which I am forming listA in above question(using one field of that). ListB is just list of string which I get from web service. Code:

//First foreach loop which I was taking about.

foreach (string A in listA)
{
  if (listB.Contains(A)
   {
   }
  else
   {
      //getting items that are added to listB
   } 
}  

//Second foreach loop which i was taking about.

foreach (string A in listB)
{
  if (listA.Contains(A)
   {
   }
  else
   {
      //getting items that are deleted from listB
   } 
}   

And then I am updating that List<custom class> accordingly. My main question is instead of using two foreach loops can I do something better?

cadrell0
  • 17,109
  • 5
  • 51
  • 69
Sai
  • 176
  • 7

3 Answers3

1

This might be more efficient (although that depends):

var notInA = listB.Except(listA).ToList();
var notInB = listA.Except(listB).ToList();
foreach (var a in notInA)
    listA.Add(a);
foreach (var b in notInB)
    listA.Remove(b);

Note that you need to implement a custom IEqualityComparer<T> if T is a custom class.

EDIT: so this is just synchronizing both lists. Maybe i've misunderstood the question but can't you simply:

listA = new List<T>(listB);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • I am doing something similar to what you have suggested.But i liked the way you did. As you can see from updated question that I cannot use listA = new List(listB); Instead of using two blocks of foreach can i do something better? Any help? – Sai Nov 16 '12 at 14:51
0

Can you use events / delegates instead of foreach ? Read a discussion here

Community
  • 1
  • 1
AYK
  • 3,312
  • 1
  • 17
  • 30
0

You should be able to make these lists observable. When one list is updated, trigger the CollectionChanged event, and add in some code to update your other list. You should be able to make this two way. See Observable Collections : Here

Furthermore, observable collections allow you to detect which kind of events occured on your collection. (Ie. Add, Remove, Replace etc.) This should help you in your process of updating the other list with the same information.

Jason Higgins
  • 1,516
  • 1
  • 17
  • 37
  • 1
    I am getting second list from service.To be more clearer i updated my question.Thanks for your inputs – Sai Nov 16 '12 at 14:55