-2

I have two List and I want to set one of them to another:

var entities = new List<Entity>() { new Entity(), new Entity(), new Entity() };

List<Entity> newCollection = new List<Entity>();

I'm doing this using two ways:

1:

newCollection = entities;

2:

foreach (var entity in entities)
{
    entity.OnDeleted += Entity_Deleted;
    newCollection.Add(entity);
}

There are many ways, but I want to use foreach, because I want to subscribe to event of Entity class and then add it to collection.
I wanted to know is there any big difference between these ways?
Will I have performance problems when I use foreach?

maccettura
  • 10,514
  • 3
  • 28
  • 35
Dilshod K
  • 2,924
  • 1
  • 13
  • 46
  • 2
    look up what references are. these are 2 completely different concepts. – Daniel A. White Jul 22 '19 at 15:14
  • Just as a note you could also do 'newCollection.AddRange(entities)', but that's off-topic :P – AidanH Jul 22 '19 at 15:20
  • 1 isn't creating a copy at all, you just have two variables pointing to the same List. – Powerlord Jul 22 '19 at 15:28
  • Your first code sample is just syntactic sugar around a call to the `.Add` method, so you've already added them to a collection. Instead of creating a new reference to the collection, you could just do `entities.ForEach(entity => entity.OnDeleted += Entity_Deleted);`, and if you want to make a copy of the list, then you can do `var newCollection = entities.ToList();` Otherwise, it's not really clear what your question is here. If you're having performance issues, please state what they are. – Rufus L Jul 22 '19 at 15:54

1 Answers1

-1

You can attach an event on the entities and then add them in another list in this way:

IList<Entity> copy = entities.Select(entity => {
    entity.OnDeleted += Entity_Deleted;
    return entity;
}).ToList();

The other approach you wrote (var copy = entities;) will just copy the reference to the first list to the new variable, but it'll be still the same instance.

The same concept it will also apply to all the entities that are in the first list: once deleted, those entities will be deleted also in the second list, unless you do a deep or shallow copy of those elements.
If you have such utility, you could approach the problem by returning the object in the Select in this way:

return entity.Copy();

Performances should not be your major concern at the moment, because, as suggested in the comments, it looks like you miss some key concepts like reference and value types, the knowledge of those things will probably radically change your further questions.

Giulio Caccin
  • 2,962
  • 6
  • 36
  • 57