Perhaps I am missing something trivial. I have a couple of List<T>
s and I need one big list from them which is a union of all the other lists. But I do want their references in that big list and not just the values/copies (unlike many questions I typically find on 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, this typically happens with
unionList = list1; //got the reference copy.
But how do I go about with the second list, list2
to add to unionList
?
I tried Add
and AddRange
but they obviously clone and not 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 am asking something that makes no sense, and something that inherently is not possible in the language..