How to remove multiple items from ObservableCollection in C#
Have you faced the problem with removing mulitple items from ObservableCollection? Ok , I know. Just use this simple generic function to remove mulitple items form ObservableCollection ( And dont't be scared of using Exceptions. Exception is nothing but a dev tool )
public static void OCRemoveMultiple<T>(ref ObservableCollection<T> inputList, IList<T> toRemoveItems)
{
REITERATE:
{
try
{
while( inputList.Intersect<T>(toRemoveItems).Any())
{
var intersectionList = inputList.Intersect<T>(toRemoveItems);
foreach (var item in intersectionList)
{
inputList.Remove(item);
}
}
}
catch (Exception)
{
goto REITERATE;
}
}
}
Here is a test case (an example) how you can use it:
ObservableCollection<object> targetList = new ObservableCollection<object>();
targetList.Add("T1");
targetList.Add("T2");
targetList.Add("B3");
targetList.Add("B4");
targetList.Add("T5");
targetList.Add("A55");
targetList.Add("X2");
IList<object> toRemove = targetList.ToList().Where(k=>k.ToString().Contains("B")).ToList();
OCRemoveMultiple(ref targetList, toRemove);
targetList.ToList().ForEach(k => Console.WriteLine(k.ToString())); // Writes "T1", "T2","T5" "A55" and "X2" to console
Post a Comment
0 Comments
Thanks!