473,772 Members | 3,672 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Creating a strongly-typed enumerable collection?

I'd like to create a strongly-typed collection of objects that are indexed
by a string value (key is a string). I'd also like to allow users to iterate
over the collection using a For-each loop where an object of the contained
type is returned (instead of just the standard DictionaryEntry object).

- only allow objects of type MyObj to be added to the collection
- return a MyObj type in the For-each loop

What's the best way to do this?

I tried to have my collection class inherit from DictionaryBase but I had
trouble getting it to return MyObj objects in the For-each. By default its
retruning DictionaryEntry objects and it wouldn't let me override the
inherited GetEnumerator() function.

I also looked at inheriting from CollectionBase but this takes an integer
for the key values.

Is creating a class that implements IEnumerable and contains a private
collection object the way to go here?

Thanks in advance for the help/advice.

Michael
Nov 20 '05 #1
4 2519
I ran into a similar problem the way that i solved it was to have a class
that inherited from CollectionBase. This class also contained a SortedList.
Anytime i added something to the list object of the collectionBase i added
it to the sorted list. By doing this i was able to access my items by key or
by index.

Shawn

"Michael K. Walter" <mk******@sqlcr aft.com> wrote in message
news:eQ******** ******@tk2msftn gp13.phx.gbl...
I'd like to create a strongly-typed collection of objects that are indexed
by a string value (key is a string). I'd also like to allow users to iterate over the collection using a For-each loop where an object of the contained
type is returned (instead of just the standard DictionaryEntry object).

- only allow objects of type MyObj to be added to the collection
- return a MyObj type in the For-each loop

What's the best way to do this?

I tried to have my collection class inherit from DictionaryBase but I had
trouble getting it to return MyObj objects in the For-each. By default its
retruning DictionaryEntry objects and it wouldn't let me override the
inherited GetEnumerator() function.

I also looked at inheriting from CollectionBase but this takes an integer
for the key values.

Is creating a class that implements IEnumerable and contains a private
collection object the way to go here?

Thanks in advance for the help/advice.

Michael

Nov 20 '05 #2
Thanks for the note Shawn.

I've tried a number of options (including your suggestion) and, while I can
set this up using various collection types as my base, I still end up in
situation where I have to have the end users of my collection cast to the
appropriate type inside of the For-each loop. So far, I've had it return
either a DictionaryEntry or generic Object type in the For-Each that I had
to manipulate/cast to MyObj type before using the retrieved object. I was
trying to avoid this but I'm beginning to think that this cannot be done in
..Net (like I can in VB6).

Example:

Dim d1 as New Dog("Duncan","G olden Retriever")
Dim d2 as New Dog("Louie", "Lab")
Dim d3 as New Dog("Butch","Be agle")

Dim Kennel as New DogCollection

Kennel.Add(d1)
Kennel.Add(d2)
Kennel.Add(d3)

Dim o as Object
Dim d as Dog

For Each o In Kennel
d = CType(o, Dog)
Console.Write(d .Name)
Next

But I'm trying to get the last lines to look like this (no Object variable
declaration or Cast required):

Dim D as Dog

For Each d in Kennel
Console.Write(d .Name)
Next

Even using IEnumerable/IEnumerator didn't help since the IEnumerator
Current() property returns a generic Object type (and I couldn't get it
compile when I changed the return type to Dog).

Am I missing something?

Michael

"Shawn Hogan" <NOSPAM> wrote in message
news:eB******** ******@TK2MSFTN GP12.phx.gbl...
I ran into a similar problem the way that i solved it was to have a class
that inherited from CollectionBase. This class also contained a SortedList. Anytime i added something to the list object of the collectionBase i added
it to the sorted list. By doing this i was able to access my items by key or by index.

Shawn

"Michael K. Walter" <mk******@sqlcr aft.com> wrote in message
news:eQ******** ******@tk2msftn gp13.phx.gbl...
I'd like to create a strongly-typed collection of objects that are indexed by a string value (key is a string). I'd also like to allow users to

iterate
over the collection using a For-each loop where an object of the contained type is returned (instead of just the standard DictionaryEntry object).

- only allow objects of type MyObj to be added to the collection
- return a MyObj type in the For-each loop

What's the best way to do this?

I tried to have my collection class inherit from DictionaryBase but I had trouble getting it to return MyObj objects in the For-each. By default its retruning DictionaryEntry objects and it wouldn't let me override the
inherited GetEnumerator() function.

I also looked at inheriting from CollectionBase but this takes an integer for the key values.

Is creating a class that implements IEnumerable and contains a private
collection object the way to go here?

Thanks in advance for the help/advice.

Michael


Nov 20 '05 #3
This class seems to do what you want when i run it with your desired code. I
ran with option strict on and it didn't need any ctype's in the client code.
Hope this helps...
Public Class DogCollection
Inherits CollectionBase
Private _keyCollection As New Collections.Sor tedList
Default Public Property Item(ByVal index As Integer) As dog
Get
Return CType(List.Item (index), dog)
End Get
Set(ByVal Value As dog)
Dim item As dog = CType(List.Item (index), dog)
Dim itemKey As String =
DirectCast(_key Collection.GetK ey(_keyCollecti on.IndexOfValue (item)), String)
_keyCollection. Item(itemKey) = Value
List.Item(index ) = Value
End Set
End Property
Default Public Property Item(ByVal key As String) As dog
Get
Return CType(_keyColle ction.Item(key) , dog)
End Get
Set(ByVal Value As dog)
Dim item As dog = CType(_keyColle ction.Item(key) , dog)
Dim itemIndex As Integer = list.IndexOf(it em)
list.Item(itemI ndex) = Value
_keyCollection. Item(key) = Value
End Set
End Property
Public Sub Add(ByVal key As String, ByVal newItem As dog)
list.Add(newIte m)
_keyCollection. Add(key, newItem)
End Sub
Public Sub Remove(ByVal key As String)
Dim item As dog = CType(_keyColle ction.Item(key) , dog)
list.Remove(ite m)
End Sub
Protected Overrides Sub OnClearComplete ()
_keyCollection. Clear()
End Sub
Protected Overrides Sub OnRemoveComplet e(ByVal index As Integer, ByVal value
As Object)
_keyCollection. Remove(_keyColl ection.GetKey(_ keyCollection.I ndexOfValue(val u
e)))
End Sub
End Class
Shawn

"Michael K. Walter" <mk******@sqlcr aft.com> wrote in message
news:e3******** ******@TK2MSFTN GP12.phx.gbl...
Thanks for the note Shawn.

I've tried a number of options (including your suggestion) and, while I can set this up using various collection types as my base, I still end up in
situation where I have to have the end users of my collection cast to the
appropriate type inside of the For-each loop. So far, I've had it return
either a DictionaryEntry or generic Object type in the For-Each that I had
to manipulate/cast to MyObj type before using the retrieved object. I was
trying to avoid this but I'm beginning to think that this cannot be done in .Net (like I can in VB6).

Example:

Dim d1 as New Dog("Duncan","G olden Retriever")
Dim d2 as New Dog("Louie", "Lab")
Dim d3 as New Dog("Butch","Be agle")

Dim Kennel as New DogCollection

Kennel.Add(d1)
Kennel.Add(d2)
Kennel.Add(d3)

Dim o as Object
Dim d as Dog

For Each o In Kennel
d = CType(o, Dog)
Console.Write(d .Name)
Next

But I'm trying to get the last lines to look like this (no Object variable
declaration or Cast required):

Dim D as Dog

For Each d in Kennel
Console.Write(d .Name)
Next

Even using IEnumerable/IEnumerator didn't help since the IEnumerator
Current() property returns a generic Object type (and I couldn't get it
compile when I changed the return type to Dog).

Am I missing something?

Michael

"Shawn Hogan" <NOSPAM> wrote in message
news:eB******** ******@TK2MSFTN GP12.phx.gbl...
I ran into a similar problem the way that i solved it was to have a class
that inherited from CollectionBase. This class also contained a SortedList.
Anytime i added something to the list object of the collectionBase i added it to the sorted list. By doing this i was able to access my items by

key or
by index.

Shawn

"Michael K. Walter" <mk******@sqlcr aft.com> wrote in message
news:eQ******** ******@tk2msftn gp13.phx.gbl...
I'd like to create a strongly-typed collection of objects that are

indexed by a string value (key is a string). I'd also like to allow users to

iterate
over the collection using a For-each loop where an object of the contained type is returned (instead of just the standard DictionaryEntry object).
- only allow objects of type MyObj to be added to the collection
- return a MyObj type in the For-each loop

What's the best way to do this?

I tried to have my collection class inherit from DictionaryBase but I had trouble getting it to return MyObj objects in the For-each. By default its retruning DictionaryEntry objects and it wouldn't let me override the
inherited GetEnumerator() function.

I also looked at inheriting from CollectionBase but this takes an integer for the key values.

Is creating a class that implements IEnumerable and contains a private
collection object the way to go here?

Thanks in advance for the help/advice.

Michael



Nov 20 '05 #4
Shawn,

I created a console app/test harness for this and it works fine...thank you.

Now I have to go back to my actual app, conpare and see where I went wrong
(I'm not really dealing with dogs and kennels - as you may have already
guessed).

Thanks again!

"Shawn Hogan" <NOSPAM> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
This class seems to do what you want when i run it with your desired code. I ran with option strict on and it didn't need any ctype's in the client code. Hope this helps...
Public Class DogCollection
Inherits CollectionBase
Private _keyCollection As New Collections.Sor tedList
Default Public Property Item(ByVal index As Integer) As dog
Get
Return CType(List.Item (index), dog)
End Get
Set(ByVal Value As dog)
Dim item As dog = CType(List.Item (index), dog)
Dim itemKey As String =
DirectCast(_key Collection.GetK ey(_keyCollecti on.IndexOfValue (item)), String) _keyCollection. Item(itemKey) = Value
List.Item(index ) = Value
End Set
End Property
Default Public Property Item(ByVal key As String) As dog
Get
Return CType(_keyColle ction.Item(key) , dog)
End Get
Set(ByVal Value As dog)
Dim item As dog = CType(_keyColle ction.Item(key) , dog)
Dim itemIndex As Integer = list.IndexOf(it em)
list.Item(itemI ndex) = Value
_keyCollection. Item(key) = Value
End Set
End Property
Public Sub Add(ByVal key As String, ByVal newItem As dog)
list.Add(newIte m)
_keyCollection. Add(key, newItem)
End Sub
Public Sub Remove(ByVal key As String)
Dim item As dog = CType(_keyColle ction.Item(key) , dog)
list.Remove(ite m)
End Sub
Protected Overrides Sub OnClearComplete ()
_keyCollection. Clear()
End Sub
Protected Overrides Sub OnRemoveComplet e(ByVal index As Integer, ByVal value As Object)
_keyCollection. Remove(_keyColl ection.GetKey(_ keyCollection.I ndexOfValue(val u e)))
End Sub
End Class
Shawn

"Michael K. Walter" <mk******@sqlcr aft.com> wrote in message
news:e3******** ******@TK2MSFTN GP12.phx.gbl...
Thanks for the note Shawn.

I've tried a number of options (including your suggestion) and, while I

can
set this up using various collection types as my base, I still end up in
situation where I have to have the end users of my collection cast to the
appropriate type inside of the For-each loop. So far, I've had it return
either a DictionaryEntry or generic Object type in the For-Each that I had to manipulate/cast to MyObj type before using the retrieved object. I was trying to avoid this but I'm beginning to think that this cannot be done

in
.Net (like I can in VB6).

Example:

Dim d1 as New Dog("Duncan","G olden Retriever")
Dim d2 as New Dog("Louie", "Lab")
Dim d3 as New Dog("Butch","Be agle")

Dim Kennel as New DogCollection

Kennel.Add(d1)
Kennel.Add(d2)
Kennel.Add(d3)

Dim o as Object
Dim d as Dog

For Each o In Kennel
d = CType(o, Dog)
Console.Write(d .Name)
Next

But I'm trying to get the last lines to look like this (no Object variable declaration or Cast required):

Dim D as Dog

For Each d in Kennel
Console.Write(d .Name)
Next

Even using IEnumerable/IEnumerator didn't help since the IEnumerator
Current() property returns a generic Object type (and I couldn't get it
compile when I changed the return type to Dog).

Am I missing something?

Michael

"Shawn Hogan" <NOSPAM> wrote in message
news:eB******** ******@TK2MSFTN GP12.phx.gbl...
I ran into a similar problem the way that i solved it was to have a class that inherited from CollectionBase. This class also contained a

SortedList.
Anytime i added something to the list object of the collectionBase i added it to the sorted list. By doing this i was able to access my items by key
or
by index.

Shawn

"Michael K. Walter" <mk******@sqlcr aft.com> wrote in message
news:eQ******** ******@tk2msftn gp13.phx.gbl...
> I'd like to create a strongly-typed collection of objects that are

indexed
> by a string value (key is a string). I'd also like to allow users to
iterate
> over the collection using a For-each loop where an object of the

contained
> type is returned (instead of just the standard DictionaryEntry

object). >
> - only allow objects of type MyObj to be added to the collection
> - return a MyObj type in the For-each loop
>
> What's the best way to do this?
>
> I tried to have my collection class inherit from DictionaryBase but I had
> trouble getting it to return MyObj objects in the For-each. By
default its
> retruning DictionaryEntry objects and it wouldn't let me override

the > inherited GetEnumerator() function.
>
> I also looked at inheriting from CollectionBase but this takes an

integer
> for the key values.
>
> Is creating a class that implements IEnumerable and contains a private > collection object the way to go here?
>
> Thanks in advance for the help/advice.
>
> Michael
>
>



Nov 20 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
1443
by: andrea | last post by:
I was thinking to code the huffman algorithm and trying to compress something with it, but I've got a problem. How can I represent for example a char with only 3 bits?? I had a look to the compression modules but I can't understand them much... Thank you very much Any good link would be appreciated of course :)
5
9793
by: | last post by:
Hi, i'm trying to run an .asp page to get an xml file off a server. I need to know what object to create. My page just runs till timeout...it bombs on the httpxml.send command. This is the code I have: set httpxml = Server.CreateObject("Msxml2.XMLHTTP.3.0") httpxml.open "GET", "http://www.txdps.state.tx.us/mpch/sb1063.xml", false ' get the requested XML data from the remote location ' change the URL as per your feed. httpxml.send
8
2028
by: cody | last post by:
i basically want to create an object which contains an array (the last element of the class). the size of the array is determined when the object is created. for performance reasons (avoiding cache misses) the whole objekt should be in one linear chunk of memory, that is the array starts where the objekt ends in memory. class Cool { Cool (int arraysize) { .. }
3
8380
by: Pattnayak | last post by:
Hi, I want to create a DTS package programatically (preferably in C#.net),which will copy all my tables from a oracle database to my sql-server database. Can anybody help me doing this??? Thanks Patnayak
4
1674
by: Tamir Khason | last post by:
I have a form. On form there is my control (all of control's assemblies signed by strong key), BUT while running I recieve he located assembly 'MyFooAssembly' is not strongly named. While looking into References node in project the assembly 'MyFooAssembly' is strong key = true. So what cna be a ptoblem??? TNX
1
1398
by: San | last post by:
Hi, Why strongly named assembly can refer other strongly named assembly ? Thanks with Regards, San.
5
1542
by: Oleg Subachev | last post by:
When I try to use strongly named assembly1 that references non-strongly named assembly2 I get the following error: "The located assembly '<assembly2 name>' is not strongly named." How can I force strongly named assembly1 to reference non-strongly named assembly2 ? --
1
1443
by: DotNetJunkies User | last post by:
I have a .NET DLL that uses ADO 2.8 DLL. I am not able to "strongly name" the .NET DLL. Any comments, work arounds ? CHDe --- Posted using Wimdows.net NntpNews Component -
11
1772
by: melon | last post by:
Let's say, I have a form class... public class MainForm : Form { private CustomClass cc; public MainForm() { DoSomething() InitializeComponent(); } /// Do something more
0
1578
by: Dave Burns | last post by:
Hi, I have a C++ managed assembly (.dll) which links to a bunch of native libraries. Everything works fine if I don't make the managed assembly a strongly named one. Once I make it a strongly named assembly by adding the following attribute: ;
0
9620
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10104
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9912
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8934
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6715
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.