How to copy list <T> without cloning

Perhaps I am missing something trivial. I have a couple List<T> , and I need one big list of them, which is the union of all the other lists. But I need their links on this long list, not just the values ​​/ copies (unlike many of the questions that I usually find in SO).

For example, I have this,

 List<string> list1 = new List<string> { "a", "b", "c" }; List<string> list2 = new List<string> { "1", "2", "3" }; var unionList = GetThatList(list1, list2); 

Suppose I get the list I want in unionList , then this should happen:

 unionList.Remove("a"); => list1.Remove("a"); unionList.Remove("1"); => list2.Remove("1"); //in other words // //unionList.Count = 4; //list1.Count = 2; //list2.Count = 2; 

To make it clear that this usually happens with

 unionList = list1; //got the reference copy. 

But how do I deal with the second list, add list2 to unionList ?

I tried Add and AddRange , but they obviously cloned and didn't copy.

 unionList = list1; unionList.AddRange(list2); //-- error, clones, not copies here. 

and

 foreach (var item in list2) { unionList.Add(item); //-- error, clones, not copies here. } 

Update: I think I'm asking for something that doesn't make sense, and something that is essentially impossible in the language ..

+7
source share
1 answer

I do not think such a class exists. You can implement it yourself. Here begins:

 class CombinedLists<T> : IEnumerable<T> // Add more interfaces here. // Maybe IList<T>, but how should it work? { private List<List<T>> lists = new List<List<T>>(); public void AddList(List<T> list) { lists.Add(list); } public IEnumerator<T> GetEnumerator() { return lists.SelectMany(x => x).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public bool Remove(T t) { foreach (List<T> list in lists) { if (list.Remove(t)) { return true; } } return false; } // Implement the other methods. } 

Here is the code you can use to verify it:

 List<string> list1 = new List<string> { "a", "b", "c" }; List<string> list2 = new List<string> { "1", "2", "3" }; CombinedLists<string> c = new CombinedLists<string>(); c.AddList(list1); c.AddList(list2); c.Remove("a"); c.Remove("1"); foreach (var x in c) { Console.WriteLine(x); } Console.WriteLine(list1.Count); Console.WriteLine(list2.Count); 

Removing items is pretty simple. But you may run into problems if you try to insert items into your combo box. This is not always well defined; the list should receive inserted elements. For example, if you have a combo box containing two empty lists, and you insert an item at index 0, should the item be added to the first or second empty list?

+12
source

All Articles