Dbloom
Dbloom

Reputation: 1402

How to set one ObservableCollection to another ObservableCollection?

Basically, I want to know if I can do this with two ObservableCollections:

oldList = newList;

I have two lists that get populated throughtout my app, and each time they get populated, I want the 'new' values to become the 'old' values, and then get a new set of values to put in the 'new' list.

is it that easy? Any other way to do this without iterating over the whole newList every time?

EDIT: This is how the new list is being populated. Basically, I just want the contents of the newList to be put into the oldList.

                foreach (object obj in ts.GetVariables())
            {
                if ((obj.ToString() != "_SMSTSReserved2") || (obj.ToString() != "OSDJoinPassword") || (obj.ToString() != "OSDLocalAdminPassword"))
                {
                    TSVar var = new TSVar();
                    var.TSVarName = obj.ToString();
                    var.TSVarValue = ts[obj.ToString()];
                    newList.Add(var);
                }
            }
            oldList.Clear();
            foreach (TSVar var in newList)
            {
                oldList.Add(var);
            }

Upvotes: 1

Views: 5464

Answers (2)

Shrinand
Shrinand

Reputation: 351

If you use the extension method listed below, what you are trying to do becomes a one liner:

oldList.Replace(newList);

I would create an Extension Method for ObservableCollection like this:

public static class ObservableCollectionExtensionMethods
    {
        public static void Replace<T>(this ObservableCollection<T> old, ObservableCollection<T> @new)
        {
            old.Clear();
            foreach (var item in @new)
            {
                old.Add(item);
            }
        }
    }

And this is how you would use it:

using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ExtensionMethods
{
    [TestClass]
    public class ObservableCollectionExtensionMethodsTest
    {
        [TestMethod]
        public void ReplaceTest()
        {
            // Arrange
            var old = new ObservableCollection<string> { "1"};
            var @new = new ObservableCollection<string> {"2"};

            // Act
            old.Replace(@new);

            // Assert
            Assert.AreEqual("2", old.First());
        }
    }
}

Upvotes: 3

Justin
Justin

Reputation: 6549

I think this is what you may be looking for? This will add everything that was in newList to your oldList.

ObservableCollection<YourType> oldList = new ObservableCollection<YourType>(newList);
newList.clear();
//put new stuff in your list here.

Upvotes: 0

Related Questions