473,796 Members | 2,661 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

List with no duplicates

Hello, Newsgroupians:

Just a quick question really quick. Does C# have a generic class that will
allow me to add only one instance of an object to the "collection " without
having me do a .Contains() or something similar?

In my case, I have a set of controls a user selects. If the user selects
the same control twice, I don't want it added again to my collection, and I
don't want to handle the exception, and I think .Contains() is too expensive.
Does anyone have any recommendations ? I've tried a Dictionary with the key
being the control as well as the value being the control, but again doing
this led to an exception. Is there any other way or generic class that I
should look at?

Thank you.
Trecius
Nov 6 '07 #1
8 37254
Trecius,

No, in .NET 3.0 and before, you have to do this yourself with a check to
Contains.

In .NET 3.5, you would use the new HashSet class.

Before that, you can use a Dictionary<TKey , TValueclass. The type
parameter TValue doesn't really matter here. It's TKey that you are
concerned about. The TKey type parameter should be set to the type of the
instances you don't want to duplicate. You can use bool for the TValue, if
you wish.

Then, before you add to the Dictionary, call Contains. If Contains
returns true, then the item exists.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Trecius" <Tr*****@discus sions.microsoft .comwrote in message
news:BA******** *************** ***********@mic rosoft.com...
Hello, Newsgroupians:

Just a quick question really quick. Does C# have a generic class that
will
allow me to add only one instance of an object to the "collection " without
having me do a .Contains() or something similar?

In my case, I have a set of controls a user selects. If the user selects
the same control twice, I don't want it added again to my collection, and
I
don't want to handle the exception, and I think .Contains() is too
expensive.
Does anyone have any recommendations ? I've tried a Dictionary with the
key
being the control as well as the value being the control, but again doing
this led to an exception. Is there any other way or generic class that I
should look at?

Thank you.
Trecius

Nov 6 '07 #2
Nicholas Paldino [.NET/C# MVP] wrote:
Trecius,

No, in .NET 3.0 and before, you have to do this yourself with a check to
Contains.

In .NET 3.5, you would use the new HashSet class.

Before that, you can use a Dictionary<TKey , TValueclass. The type
parameter TValue doesn't really matter here. It's TKey that you are
concerned about. The TKey type parameter should be set to the type of the
instances you don't want to duplicate. You can use bool for the TValue, if
you wish.

Then, before you add to the Dictionary, call Contains. If Contains
returns true, then the item exists.
It should also be noted that with dictionaries, Contains is really not
an expensive call. It could be if the number of items was really large,
but sounds like the OP is talking about user controls that a user would
select, something that isn't likely to come anywhere near having enough
to cause any performance issues with a call to Contains.
--
Tom Porterfield
Nov 6 '07 #3
On 2007-11-06 13:18:32 -0800, Tom Porterfield <tp******@mvps. orgsaid:
[...]
Then, before you add to the Dictionary, call Contains. If
Contains returns true, then >the item exists.

It should also be noted that with dictionaries, Contains is really not
an expensive call. It could be if the number of items was really
large, but sounds like the OP is talking about user controls that a
user would select, something that isn't likely to come anywhere near
having enough to cause any performance issues with a call to Contains.
I would reverse that. Using a Dictionary<>, the call should not be
expensive regardless, even if the number of elements is large.
Assuming this is a case of dealing with user controls, a plain old tree
traversal is likely to be plenty fast as long as it's not the primary
thing that the program is doing (and it's hard to imagine why it would
be).

Pete

Nov 7 '07 #4
On Nov 6, 4:05 pm, "Nicholas Paldino [.NET/C# MVP]"
<m...@spam.guar d.caspershouse. comwrote:
Trecius,

No, in .NET 3.0 and before, you have to do this yourself with a check to
Contains.

In .NET 3.5, you would use the new HashSet class.

Before that, you can use a Dictionary<TKey , TValueclass. The type
parameter TValue doesn't really matter here. It's TKey that you are
concerned about. The TKey type parameter should be set to the type of the
instances you don't want to duplicate. You can use bool for the TValue, if
you wish.

Then, before you add to the Dictionary, call Contains. If Contains
returns true, then the item exists.

--
- Nicholas Paldino [.NET/C# MVP]
- m...@spam.guard .caspershouse.c om

"Trecius" <Trec...@discus sions.microsoft .comwrote in message

news:BA******** *************** ***********@mic rosoft.com...
Hello, Newsgroupians:
Just a quick question really quick. Does C# have a generic class that
will
allow me to add only one instance of an object to the "collection " without
having me do a .Contains() or something similar?
In my case, I have a set of controls a user selects. If the user selects
the same control twice, I don't want it added again to my collection, and
I
don't want to handle the exception, and I think .Contains() is too
expensive.
Does anyone have any recommendations ? I've tried a Dictionary with the
key
being the control as well as the value being the control, but again doing
this led to an exception. Is there any other way or generic class that I
should look at?
Thank you.
Trecius- Hide quoted text -

- Show quoted text -
Do you really have to call Contains before updating a Dictionary ?

I mean, I thought that a Dictionary could not _inherently_ contain
multiple entries, because after all it is just a Key-Value pair, not a
Key-ListOfValues pair ?

EG,
The code below should not except and should not store any duplicates!

Dictionary[ objectA.UniqueI D ] = "specialVal ue";
Dictionary[ objectA.UniqueI D ] = "anotherSpecial Value"

Right ?

Nov 7 '07 #5
On Nov 6, 3:46 pm, Trecius <Trec...@discus sions.microsoft .comwrote:
Hello, Newsgroupians:

Just a quick question really quick. Does C# have a generic class that will
allow me to add only one instance of an object to the "collection " without
having me do a .Contains() or something similar?

In my case, I have a set of controls a user selects. If the user selects
the same control twice, I don't want it added again to my collection, and I
don't want to handle the exception, and I think .Contains() is too expensive.
Does anyone have any recommendations ? I've tried a Dictionary with the key
being the control as well as the value being the control, but again doing
this led to an exception. Is there any other way or generic class that I
should look at?

Thank you.

Trecius
My solution is outside of the Key-Value box :)

Since we want the list to contain unique values, only store those
values as the KEYS in the Dictionary. The dictionary , by definition,
does not store more than one value per key. You can then copy the
Dictionary.Keys property into a list and rest assured that there are
no duplicates.

Nov 7 '07 #6
On Nov 7, 12:58 pm, Norapinephrine <N.AhmedRo...@g mail.comwrote:
On Nov 6, 3:46 pm, Trecius <Trec...@discus sions.microsoft .comwrote:


Hello, Newsgroupians:
Just a quick question really quick. Does C# have a generic class that will
allow me to add only one instance of an object to the "collection " without
having me do a .Contains() or something similar?
In my case, I have a set of controls a user selects. If the user selects
the same control twice, I don't want it added again to my collection, and I
don't want to handle the exception, and I think .Contains() is too expensive.
Does anyone have any recommendations ? I've tried a Dictionary with the key
being the control as well as the value being the control, but again doing
this led to an exception. Is there any other way or generic class that I
should look at?
Thank you.
Trecius

My solution is outside of the Key-Value box :)

Since we want the list to contain unique values, only store those
values as the KEYS in the Dictionary. The dictionary , by definition,
does not store more than one value per key. You can then copy the
Dictionary.Keys property into a list and rest assured that there are
no duplicates.- Hide quoted text -

- Show quoted text -
Let me expand :

object inputValue = GetUserSelected ValueFromGUI();

dictionary[inputValue] = 99; // the only thing important here is that
we stored inputValue as a KEY in the dictionary.

....

List<objectnoDu plicatesListOfU serInput = dictionary.Keys ;

Hope this helps!

Nov 7 '07 #7
On 2007-11-07 09:55:53 -0800, Norapinephrine <N.**********@g mail.comsaid:
[...]
Do you really have to call Contains before updating a Dictionary ?
No, you're right. You can catch an exception instead when calling
Add(), or you can use the Item property as you've suggested.
I mean, I thought that a Dictionary could not _inherently_ contain
multiple entries, because after all it is just a Key-Value pair, not a
Key-ListOfValues pair ?
The keys must be unique, yes.
EG,
The code below should not except and should not store any duplicates!

Dictionary[ objectA.UniqueI D ] = "specialVal ue";
Dictionary[ objectA.UniqueI D ] = "anotherSpecial Value"

Right ?
Yes. If the key doesn't already exist, a set operation on the Item
property will create a new entry in the Dictionary with the specified
value. If the key does already exist, the value associated with the
key will be replaced by the specified value.

Pete

Nov 7 '07 #8
Just have:

Hashtable ht = new Hashtable ();

Then use:
this.ht [key] = null;

Using "= 99" as you did raises boxing issues and could create a huge
performance hit.

Hilton
Nov 7 '07 #9

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

Similar topics

22
35492
by: christof hoeke | last post by:
hello, this must have come up before, so i am already sorry for asking but a quick googling did not give me any answer. i have a list from which i want a simpler list without the duplicates an easy but somehow contrived solution would be >>> a = >>> d = {}.fromkeys(a) >>> b = d.keys()
3
4687
by: Mark V. | last post by:
Here's what I have and I'm stumped. I have a table that has several thousand names and addresses. I only want to send to one address in a household. So what I would like to do is create a new column that runs a macro or whatever it takes to flag records so they are housholded. Some records have a Father and son at the same address, so I would only want to generate a count in my query that gives me one record for that household, a head of...
24
5779
by: Robin Cole | last post by:
I'd like a code review if anyone has the time. The code implements a basic skip list library for generic use. I use the following header for debug macros: /* public.h - Public declarations and macros */ #ifndef PUBLIC #define PUBLIC
2
2205
by: Zak McGregor | last post by:
Hi all I have a table, for simplicity's sake containing one field, called unid. for example, select unid, oid from table gives me something like this: unid | oid ---------+---------
4
2481
by: Killer42 | last post by:
Hi all. Sorry, this is probably a really simple one but I'm having some difficulty with it, and don't have much time to devote to it right now. I need to find all the records which have duplicates (on two fields) in another table. In Access 2003, the "Find duplicates wizard" will produce a query to list duplicates within the one table, but what about when they're in a different one? In other words, I want to select all records in table...
2
1557
by: kalar | last post by:
I have an exercise which says: create a data type called total integers (double(same) values are not allowed) How will i do this? I have already a function removeduplicates from another program which i create,that has as an argument the head of a list and removes the duplicates. So in my exercise what is best? to create first the hole list and in the end call removeduplicates? or should i make a check before i add each node?
1
3329
by: AndyB | last post by:
I have found a lot of material on removing duplicates from a list, but I am trying to find the most efficient way to just check for the existence of duplicates in a list. Here is the best I have come up with so far: CheckList = for x in self.__XRList] FilteredList = filter((lambda x:x != 0),CheckList) if len(FilteredList) len(sets.Set(FilteredList)): return False The first statement pulls the slice out of a matrix I need to check.
22
6921
by: Simon Forman | last post by:
Is there a more efficient way to do this? def f(L): '''Return a set of the items that occur more than once in L.''' L = list(L) for item in set(L): L.remove(item) return set(L)
3
1639
by: Mike Copeland | last post by:
How do I work with a std::list that might have multiple objects having the same "key", but which have other data that is different? Here's code that compiles, but doesn't do quite what I expect: (Please note that there's some specialized I/o code here, but the logic flow should be clear...) struct GenCheck // Gender Check data { char genCode; int useCount;
4
4768
by: moon24 | last post by:
Hi im working with linked list and i have to implement a function that deletes the duplicates of a number. for example if given 2 7 1 7 12 7 then the result should be 2 7 1 12 here is what I have: #include <iostream> using namespace std; class NumberList {
1
10182
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
10017
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
9055
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...
1
7552
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
6793
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
5445
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...
1
4120
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3734
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2928
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.