473,761 Members | 3,542 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

type-safe collection

I would like to make a strongly typed, sortable collection by leveraging a
Framework class. I began by looking at CollectionBase but it doesn't have
built-int sorting. I would prefer to derive from ArrayList, but if I code
an Add(MyElement) method, the original Add(object) remains exposed,
compromising type safety. I know this must be a common task, how to do it?
Thanks,
Gary
Nov 15 '05 #1
7 2805
CollectionBase uses an array list internally(the protected InnerList
property). You should be able to simply call down to the sort method on that
via your own using hte containment method Jeff Louie suggested.
"Gary" <gf***@thoughtv ector.com> wrote in message
news:40******** *************** @news.newshosti ng.com...
I would like to make a strongly typed, sortable collection by leveraging a
Framework class. I began by looking at CollectionBase but it doesn't have
built-int sorting. I would prefer to derive from ArrayList, but if I code
an Add(MyElement) method, the original Add(object) remains exposed,
compromising type safety. I know this must be a common task, how to do it? Thanks,
Gary

Nov 15 '05 #2
Gary,
I would like to make a strongly typed, sortable collection by leveraging a
Framework class. I began by looking at CollectionBase but it doesn't have
built-int sorting. CollectionBase has "built-in" sorting by virtue its a wrapper around an
ArrayList, the ArrayList itself is exposed via the protected
CollectionBase. InnerList property.

If your class needs to support Sort itself, I would recommend delegation to
the InnerList sort methods.

Something like (untested):

using System.Collecti ons;

class MyCollection : CollectionBase
{

...

void Sort()
{
base.InnerList. Sort()
}
void Sort(IComparer comparer)
{
base.InnerList. Sort(comparer)
}
void Sort(int index, int count, IComparer comparer)
{
base.InnerList. Sort(index, count, comparer)
}
}

Hope this helps
Jay

"Gary" <gf***@thoughtv ector.com> wrote in message
news:40******** *************** @news.newshosti ng.com... I would like to make a strongly typed, sortable collection by leveraging a
Framework class. I began by looking at CollectionBase but it doesn't have
built-int sorting. I would prefer to derive from ArrayList, but if I code
an Add(MyElement) method, the original Add(object) remains exposed,
compromising type safety. I know this must be a common task, how to do it? Thanks,
Gary

Nov 15 '05 #3
Hi Gary,

Please find below an example of a strong typed collection, as you can see
the correct way of doing so is extending CollectionBase.
The only functionality not provided is Sort, for this I implemented a class
: ClassSorter , it use reflection to sort any class based on a property
without need anything from the sortee class.
If you have any doubt let me know.

Pd:
The code is not well commented as I got it from the current working project
that is not well documented yet.
The Collection is a collection of a class type named Location, you need to
change this to your correct type.
If you look the Sort method of the collection class you will see that the
first parameter is the name of the property that will be used as sort
criteria.

Hope this help,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
public class LocationCollect ion:CollectionB ase
{
public Location Insert( int index, Location newelem )
{
this.InnerList. Insert( index, newelem);
return newelem;
}
public Location Add( Location newelem)
{
this.InnerList. Add( newelem);
return newelem;
}

public Location this[int index]
{
get
{
return (Location) InnerList[index];
}
set
{
InnerList[index] = value;
}
}

public Location Find(int id)
{
foreach(Locatio n current in InnerList)
if ( current.ID == id )
return current;
return null;
}

public void Remove( Location elem)
{
InnerList.Remov e( elem);

}
public LocationCollect ion(){}
private LocationCollect ion( ArrayList newarray)
{
InnerList.Clear ();
foreach( Location location in newarray)
{
Add( location);
}
}
public LocationCollect ion Sort( string sortParam,
fatalcrashCore. SortDirection direction)
{
ArrayList newlist = (ArrayList)Inne rList.Clone();
ClassSorter sorter = new ClassSorter( sortParam, SortByType.Prop erty,
direction);
newlist.Sort( sorter);
return new LocationCollect ion( newlist);
}

public LocationCollect ion Clone()
{
return new LocationCollect ion( InnerList);
}
public LocationCollect ion Search(FilterCo llection filters, bool AND)
{
LocationCollect ion filtered = new LocationCollect ion ();
foreach(Locatio n point in InnerList)
{
bool matched = false;
foreach(FilterB ase filter in filters)
if ( filter.Match(po int) )
{
matched = true;
if ( !AND )
break;
}
else
{
if ( AND )
{
matched = false;
break;
}
}
if ( matched )
filtered.Add( point);

}
return filtered;
}

}

public class ClassSorter: IComparer
{
protected string sortBy;
protected SortByType sortByType;
protected SortDirection sortDirection;
#region Constructors
public ClassSorter(str ing sortBy, SortByType sortByType, SortDirection
sortDirection)
{
this.sortBy = sortBy;
this.sortByType = sortByType;
this.sortDirect ion = sortDirection;
}
#endregion

int Compare( object x, object y, string comparer)
{
if ( comparer.IndexO f( ".") != -1 )
{
//split the string
string[] parts = comparer.Split( new char[]{ '.'} );
return Compare( x.GetType().Get Property( parts[0]).GetValue(x, null) ,
y.GetType().Get Property( parts[0]).GetValue(y, null) , parts[1]
);
}
else
{
IComparable icx, icy;
icx =
(IComparable)x. GetType().GetPr operty( comparer).GetVa lue(x, null);
icy =
(IComparable)y. GetType().GetPr operty( comparer).GetVa lue(y, null);

if ( x.GetType().Get Property(compar er).PropertyTyp e ==
typeof(System.S tring) )
{
icx = (IComparable) icx.ToString(). ToUpper();
icy = (IComparable) icy.ToString(). ToUpper();
}

if(this.sortDir ection == SortDirection.D escending)
return icy.CompareTo(i cx);
else
return icx.CompareTo(i cy);
}

}

public int Compare(object x, object y)
{
return Compare( x, y, sortBy);
}

}

public enum SortByType
{
Method = 0,
Property = 1
}

public enum SortDirection
{
Ascending = 0,
Descending = 1
}

"Gary" <gf***@thoughtv ector.com> wrote in message
news:40******** *************** @news.newshosti ng.com...
I would like to make a strongly typed, sortable collection by leveraging a
Framework class. I began by looking at CollectionBase but it doesn't have
built-int sorting. I would prefer to derive from ArrayList, but if I code
an Add(MyElement) method, the original Add(object) remains exposed,
compromising type safety. I know this must be a common task, how to do it? Thanks,
Gary

Nov 15 '05 #4
Thanks for all the great suggestions, folks, stuff for me to chew on!
Gary

"Gary" <gf***@thoughtv ector.com> wrote in message
news:40******** *************** @news.newshosti ng.com...
I would like to make a strongly typed, sortable collection by leveraging a
Framework class. I began by looking at CollectionBase but it doesn't have
built-int sorting. I would prefer to derive from ArrayList, but if I code
an Add(MyElement) method, the original Add(object) remains exposed,
compromising type safety. I know this must be a common task, how to do it? Thanks,
Gary

Nov 15 '05 #5
Thanks, I wasn't aware of this. This looks like the least effort route to
the solution.
Gary

"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> wrote in message
news:et******** ******@TK2MSFTN GP09.phx.gbl...
Gary,
I would like to make a strongly typed, sortable collection by leveraging a Framework class. I began by looking at CollectionBase but it doesn't have built-int sorting. CollectionBase has "built-in" sorting by virtue its a wrapper around an
ArrayList, the ArrayList itself is exposed via the protected
CollectionBase. InnerList property.

If your class needs to support Sort itself, I would recommend delegation

to the InnerList sort methods.

Something like (untested):

using System.Collecti ons;

class MyCollection : CollectionBase
{

...

void Sort()
{
base.InnerList. Sort()
}
void Sort(IComparer comparer)
{
base.InnerList. Sort(comparer)
}
void Sort(int index, int count, IComparer comparer)
{
base.InnerList. Sort(index, count, comparer)
}
}

Hope this helps
Jay

"Gary" <gf***@thoughtv ector.com> wrote in message
news:40******** *************** @news.newshosti ng.com...
I would like to make a strongly typed, sortable collection by leveraging a Framework class. I began by looking at CollectionBase but it doesn't have built-int sorting. I would prefer to derive from ArrayList, but if I code an Add(MyElement) method, the original Add(object) remains exposed,
compromising type safety. I know this must be a common task, how to do

it?
Thanks,
Gary


Nov 15 '05 #6
Gary,
FYI: the DictionaryBase is a wrapper around Hashtable, the Hashtable itself
is exposed via the DictionaryBase. InnerHashtable.

I actually wrote my own DictionaryBase & CollectionBase, that allow the
developer to can change the wrapped collection. Which reminds me, I need to
post them someplace convenient for others ;-)

Hope this helps
Jay

"Gary" <gf***@thoughtv ector.com> wrote in message
news:40******** **************@ news.newshostin g.com...
Thanks, I wasn't aware of this. This looks like the least effort route to
the solution.
Gary

"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> wrote in message
news:et******** ******@TK2MSFTN GP09.phx.gbl...
Gary,
I would like to make a strongly typed, sortable collection by
leveraging
a Framework class. I began by looking at CollectionBase but it doesn't have built-int sorting. CollectionBase has "built-in" sorting by virtue its a wrapper around an
ArrayList, the ArrayList itself is exposed via the protected
CollectionBase. InnerList property.

If your class needs to support Sort itself, I would recommend delegation

to
the InnerList sort methods.

Something like (untested):

using System.Collecti ons;

class MyCollection : CollectionBase
{

...

void Sort()
{
base.InnerList. Sort()
}
void Sort(IComparer comparer)
{
base.InnerList. Sort(comparer)
}
void Sort(int index, int count, IComparer comparer)
{
base.InnerList. Sort(index, count, comparer)
}
}

Hope this helps
Jay

"Gary" <gf***@thoughtv ector.com> wrote in message
news:40******** *************** @news.newshosti ng.com...
I would like to make a strongly typed, sortable collection by
leveraging a Framework class. I began by looking at CollectionBase but it doesn't have built-int sorting. I would prefer to derive from ArrayList, but if I code an Add(MyElement) method, the original Add(object) remains exposed,
compromising type safety. I know this must be a common task, how to
do it?
Thanks,
Gary



Nov 15 '05 #7
Strong-Typed collections based on CollectionBase, or an ArrayList???? Sure
you could wrap it up and make it a strong-typed collection, but everything
is still going to get cast as an object, and that will have a serious affect
on performance. The easiest way to learn strong type collections or have
one made for you is to use CollectionGen for CodeSmith:

http://www.sellsbrothers.com/tools/
http://www.kynosarges.de/Templates.html

I now write all my collections manually and I can always get better
performance out of them than the standard .NET collection.

Hope this helps,
Jacob
"Gary" <gf***@thoughtv ector.com> wrote in message
news:40******** *************** @news.newshosti ng.com...
I would like to make a strongly typed, sortable collection by leveraging a
Framework class. I began by looking at CollectionBase but it doesn't have
built-int sorting. I would prefer to derive from ArrayList, but if I code
an Add(MyElement) method, the original Add(object) remains exposed,
compromising type safety. I know this must be a common task, how to do it? Thanks,
Gary

Nov 15 '05 #8

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

Similar topics

21
4529
by: Batista, Facundo | last post by:
Here I send it. Suggestions and all kinds of recomendations are more than welcomed. If it all goes ok, it'll be a PEP when I finish writing/modifying the code. Thank you. .. Facundo
3
510
by: dgaucher | last post by:
Hi, I want to consume a Web Service that returns a choice, but my C++ client always receives the same returned type. On the other hand, when I am using a Java client, it is working fine (of course, the generated proxy is not the same). When I am looking at the C++ generated code, it seems fine, but when I am executing the code, I always get the first choice type.
6
2691
by: S.Tobias | last post by:
I'm trying to understand how structure type completion works. # A structure or union type of unknown # content (as described in 6.7.2.3) is an incomplete type. It # is completed, for all declarations of that type, by ^^^ # declaring the same structure or union tag with its defining # content later in the same scope. ^^^^^ (6.2.5#23)
0
1776
by: Chris Fink | last post by:
When I am consuming a webservice, an object has an undefined value (inq3Type.Call3Data). I do not completely understand why this is happening and apologize for the vague question. My assumption is that the WSDL is defined incorrectly and .NET cannot parse the types. Any help is greatly appreciated! CustDDGSvc ws = new CustDDGSvc(); ws.Url = "http://dmapfra003.decisionone.com:8080/JISOAP/CustDDGSvc"; // don't understand why the...
669
26181
by: Xah Lee | last post by:
in March, i posted a essay “What is Expressiveness in a Computer Language”, archived at: http://xahlee.org/perl-python/what_is_expresiveness.html I was informed then that there is a academic paper written on this subject. On the Expressive Power of Programming Languages, by Matthias Felleisen, 1990. http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf
3
2829
by: john | last post by:
Hi to All To demonstrate: public class MyBaseGenericClass<T> { } public class MyGenericClass1<T: MyBaseGenericClass<T> {
7
7817
by: Sky | last post by:
I have been looking for a more powerful version of GetType(string) that will find the Type no matter what, and will work even if only supplied "{TypeName}", not the full "{TypeName},{AssemblyName}" As far as I know yet -- hence this question -- there is no 'one solution fits all', but instead there are several parts that have to be put together to check. What I have so far is, and would like as much feedback as possible to ensure I've...
9
3876
by: weirdwoolly | last post by:
Hopefully someone will be able to help. I have written a stored procedure in C++ called from a Java test harness to validate the graphic data types in C++ and their use. I have declared the vargraphic input parameters along the following lines in i_vargraphic100 vargraphic(100) and they are populated from String's in java.
5
3173
by: JH | last post by:
Hi I found that a type/class are both a subclass and a instance of base type "object". It conflicts to my understanding that: 1.) a type/class object is created from class statement 2.) a instance is created by "calling" a class object.
3
17126
by: amanjsingh | last post by:
Hi, I am trying to implement Java Web Service using Apache Axis2 and Eclipse as a tool. I have created the basic code and deployed the service using various eclipse plugin but when I try to invoke the service using client stub, I get this error... Exception in thread "main" java.lang.Error: Unresolved compilation problems: org.apache cannot be resolved to a type org.apache cannot be resolved to a type org.apache cannot be resolved to a...
0
9377
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
10136
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9989
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...
0
9811
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
8814
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 projectplanning, coding, testing, and deploymentwithout 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...
1
7358
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6640
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
5266
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...
3
2788
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.