I have a subclass of List<Location>
called LocationList
. This is a convenient way for us to add other properties (like IsExpanded
and such that we can use in the UI. Good enough. But now, we want each location to be aware of its parent. As such, we need to be notified when something is added to LocationList, but you can't override Add
and Remove
. While we can use ObservableCollection, that's more of a View/ViewModel construct. This is pure model data.
Sure we could manually set the parent when adding it to the collection, but I hate non-automated logic like that as there's nothing to enforce its set correctly. Letting the collection (well, List) automatically say 'Hey... you're being added, so I'll set your parent to the class that owns me." is what I'm after.
My thought is to instead of subclass List<Location>
to instead just create a straight class that uses a List<Location>
internally, and then I can simply expose my own Add/Remove methods and handle the adjustments to 'Parent' in there. However, doing so breaks being able to enumerate over the internal collection since it's inside.
That said, is there any way to either listen to changes to List<Location>
, or at least delegate its IEnumerable
interface from the wrapped object to its wrapper?
List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.
if (myList. Contains(myString)) string element = myList. ElementAt(myList. IndexOf(myString));
C# List (List<T>) In c#, List is a generic type of collection, so it will allow storing only strongly typed objects, i.e., elements of the same data type. The size of the list will vary dynamically based on our application requirements, like adding or removing elements from the list.
Change your LocationList to inherit from Collection<Location>
instead. I don't know why List<T>
isn't sealed, but it's not extendable.
Source: Framework Design Guidelines, Second Edition, Page 251:
List<T>
is optimized for performance and power at the cost of cleanness of the APIs and flexibility.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With