There is a collection of Product objects, each of which contains two collections of User objects and one main Creator user:

 public class User { public int Id { get; set; } public string Name { get; set; } } public class Product { public int Id { get; set; } public string Title { get; set; } public User Creator { get; set; } public ICollection<User> UsersAsMain { get; set; } public ICollection<User> UsersAsReserve { get; set; } } 
  • User objects in both lists of the same Product object are all different, do not repeat.
  • A copy (single instance) of a Creator object may be in one of the lists.
  • User objects that are in the same Product may also be in the rest.

You need to go through all users and, if a copy of it is found, assign it a link to the main object. As a result, all the same users must refer to the same object in memory.

How to create a LINQ query (possibly several) to check and redefine links? It is enough to compare by Id .

  • The "copy (separate instance) of the Creator object" is this that you create a separate User clone and push it into the Creator ? Or I do not understand something. - Sublihim
  • Perhaps you can help stackoverflow.com/questions/398871/… - Trymount
  • @Sublihim, right, Creator may also be present in one of the lists. - tretetex
  • Why do you create copies of objects? - Sublihim
  • Simply, I hope, you understand, if you did once a var user = new User(...) and then insert this user in the lists and in the Creator, then only references to a single object in the memory will be stored there? - Sublihim

1 answer 1

Create an object that stores links to users.

 Dictionary<int, User> users = new Dictionary<int, User>(); 

We go through all the collections, we take User, we search in users , if we find it - we substitute a link, if not - we add it to users

 foreach (Product product in products) { foreach (User user in product.UsersAsMain.ToArray()) { if (users.ContainsKey(user.Id)) { product.UsersAsMain.Remove(user); product.UsersAsMain.Add(users[user.Id]); } else { users.Add(user.Id, user); } } foreach (User user in product.UsersAsReserve.ToArray()) { if (users.ContainsKey(user.Id)) { product.UsersAsReserve.Remove(user); product.UsersAsReserve.Add(users[user.Id]); } else { users.Add(user.Id, user); } } if (users.ContainsKey(product.Creator.Id)) { product.Creator = users[product.Creator.Id]; } else { users.Add(product.Creator.Id, product.Creator); } } 

Of course, this is a big crutch. You would have to disassemble how clones turned out in these collections.