I have an object (MyObj) that itself will hold a List of other objects of various types and I want to count them as they are added to MyObj. That’s the simple explanation, anyways…
I have an Interface (MyInterface) that all sub-objects agree to. MyObj has a List(Of MyInterface) property that all the sub-objects are added to. MyInterface will expose a property that lets me figure out what subtype each object is (the sub-objects do not inherit from MyObj at all).
But I want to count these sub-objects as they are added to the list, and I’m trying to find a good way to do it. I don’t need to worry about decrementing the count, as I am going to mimic the behavior of String and just create a new instance of MyObj if it ever changes, so all my counts will start from 0. This’ll hit the garbage collector a bit, but I think this will allow for simpler (and safer) code.
The only sane way I can think of to count objects is a very large structure in MyObj that uses bytes to hold the count (I will never have more than 255 of any given sub-object in the list in MyObj). But, even using bytes, this structure will be about 100-200 bytes big in memory (I have that many sub-objects), and I anticipate having a fair amount of MyObj copies running around, too.
I’ll also need a large Select Case to know which count property to increment when a new sub-object is added. This seems to be a bit ugly, though I’ve used this approach several times already.
What I am wondering is, instead of counting each object as it is added to the list, is there some way to query the list and count only the objects of a specific type? I wouldn’t need to store this anywhere, since it would be dynamic, like querying a database and asking for a count of a specific column or type of record.
I suspect Linq can do this, but Linq is also quite slow. Are there other approaches? Perhaps a predicate of some kind?
EDIT: I tink I want something like this in Linq, but I’m a bit confused on how to format it in VB (I am not a C# guy):
From i in MyObj.MyList Group i by i.GetType into g Let c as Int32 = g.Count()
And that’s it so far. I am still googling, but I am getting way too many C# and SQL references.
1 Answer