Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Lists reference with two?

Tags:

c#

list

reference

I need 2 lists which are separate and one list containing the items of these two lists.

List<int> list1 = new List<int>();
List<int> list2 = new List<int>();

List<int> list3 = list1 & list2

When I add some integers in list1, I would like them to appear in list3 as well. I want the same behavior when a new item is added into list2.

A reference of more than one lists.

Is this possible?

like image 968
NiTeC57 Avatar asked Sep 01 '26 13:09

NiTeC57


2 Answers

No, you can't do that with List<T> directly. However, you could declare:

IEnumerable<int> union = list1.Union(list2);

Now that will be lazily evaluated - every time you iterate over union, it will return every integer which is in either list1 or list2 (or both). It will only return any integer once.

If you want the equivalent but with concatenation, you can use

IEnumerable<int> concatenation = list1.Concat(list2);

Again, that will be lazily evaluated.

As noted in comments, this doesn't expose all the operations that List<T> does, but if you only need to read from the "combined integers" (and do so iteratively rather than in some random access fashion) then it may be all you need.

like image 51
Jon Skeet Avatar answered Sep 04 '26 04:09

Jon Skeet


Is it possible?

Not with List since it's a static data structure - however you could use a query that is the concatenation of the two lists. Then whenever you enumerate the query it will show the current contents:

List<int> list1 = new List<int>();
List<int> list2 = new List<int>();

IEnumerable<int> list3 = list1.Concat(list2);

But as soon as you materialize the query into a data structure (by calling ToList, ToArray, etc.) the contents are static and will not update if one of the underlying lists updates.

like image 25
D Stanley Avatar answered Sep 04 '26 04:09

D Stanley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!