I have a collection of objects A. Each A has a field that correlates with object B, from which I have another collection. In other words, each B is attached to a subset of the As collection (but only conceptually, not code). This field - AB correlation - can change throughout the life of the system. There are system requirements that prevent this structure from changing.
If I need to repeatedly perform operations on each B-set A, it would be better to repeat using the Where () method in collection A or create another collection belonging to B and a class that controls the addition and removal of the corresponding items.
Let me see if I can fix this in code:
class A { public B owner; ... } class B { ... } class FrequentlyCalledAction { public DoYourThing(B current) { List<A> relevantItems = listOfAllAItems.Where(x => x.owner == current).ToList() foreach (A item in relevantItems) { ... } } }
Vs:
class A { public B owner; ... } class B { public List<A> itsItems; } class FrequentlyCalledAction { public void DoYourThing(B current) { foreach (A item in current.itsItems) { ... } } } class AManager { public void moveItem(A item, B from, B to) { from.itsItems.remove(item); to.itsItems.add(item); } }
source share