-2

How do you create a new list with two lists inside of it (deep copy instead of reference). I know you can't do the following, but I'm looking for Something like the following where the new list doesn't have reference to the old list elements:

List<object> a = new List<object>() {c, d};
List<object> b = new List<object>() {e, f};

List<object> g = new List<object>(a, b);
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
rickster26ter1
  • 373
  • 3
  • 10
  • 2
    use one of theses ideas to clone the objects: https://stackoverflow.com/questions/78536/deep-cloning-objects And than add those clones into the new list eg `a.Concat(b).Select(x => x.Clone()).ToList();` – Rand Random Mar 12 '23 at 22:28

2 Answers2

-1
List<int> a = new List<int>() { 1, 2 };
List<int> b = new List<int>() { 3, 4 };
List<List<int>> g = new List<List<int>>() { a, b };
marepbc
  • 1
  • 2
  • It's a good idea, but I don't want a list of lists. I just want one list where all the elements from both lists are inside of it without additional compression. – rickster26ter1 Mar 12 '23 at 22:45
-1

if you want to combine two lists into one of each, you can use .AddRange():

List<object> list1 = new() { "a", "b", "c" };
List<object> list2 = new() { "d", "e", "f" };

list1.AddRange(list2);
// or
list2.AddRange(list1);

If you want to create a separated list and keep the original ones, you can use .Concat():

List<object> list1 = new() { "a", "b", "c" };
List<object> list2 = new() { "d", "e", "f" };

List<object> list3 = list1.Concat(list2).ToList();

Feel free to search such basic questions via Search here - it is quite useful! A friendly tip from the alike beginner.

Humble Newbie
  • 98
  • 1
  • 11