473,765 Members | 1,909 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

List<T>.Contain s

JB
I've created a generic of type List<T> where T is a custom class. I
need to use the List<T>.Contain s method. I know I need to implement
the IEqualityCompar er but I can't seem to get the Contains method to
execute my Equals code. What am I doing wrong?

T is the following

NameValue : IEqualityCompar er<NameValue>
{
public string Text;
public string Value;

public bool Equals(NameValu e nv1, NameValue nv2)
{
if (nv1.Key == nv2.Key && nv1.Value == nv2.Value)
return true;
else
return false;
}

public int GetHashCode(Nam eValue nv)
{
return nv.Key.GetHashC ode();
}
}

Thanks
JB

May 4 '06 #1
3 21666
"JB" <jb*****@gmail. com> wrote:
I've created a generic of type List<T> where T is a custom class. I
need to use the List<T>.Contain s method. I know I need to implement
the IEqualityCompar er but I can't seem to get the Contains method to
execute my Equals code. What am I doing wrong?


You don't need to implement IEqualityCompar er. See the code below. NB.
The documentation says that List<T>.Contain s uses
EqualityCompare r.Default, so you providing your own IEqualityCompar er
isn't going to do any good. But read the documentation for
EqualityCompare r.Default. It says it will use System.IEquatab le if T
supports it, but otherwise will fall back on the overrides of
Object.Equals and Object.GetHashC ode. (and I've provided
implementations of these two).

class NameValue
{ public string Text, Value;
public override bool Equals(object obj)
{ NameValue that = obj as NameValue; if (that==null) return false;
return (this.Text==tha t.Text && this.Value==tha t.Value);
}
public override int GetHashCode()
{ return Text.GetHashCod e() ^ Value.GetHashCo de();
}
}

public static void Main(string[] args)
{ List<NameValue> mylist = new List<NameValue> ();
NameValue x = new NameValue(); x.Text="hello"; x.Value="World" ;
mylist.Add(x);
NameValue y = new NameValue(); y.Text="hello"; y.Value="World" ;
bool c = mylist.Contains (y);
}
NB. For your NameValue, I'd be inclined to make it a struct. In which
case you should also provide == and !=, just for sake of good
programming practice. Here:
struct NameValue
{ public string Text, Value;

public override bool Equals(object obj)
{ if (obj==null || obj.GetType()!= this.GetType()) return false;
return this == ((NameValue)obj );
}

public override int GetHashCode()
{ return Text.GetHashCod e() ^ Value.GetHashCo de();
}

public static bool operator != (NameValue x, NameValue y)
{ return !(x==y);
}

public static bool operator == (NameValue x, NameValue y)
{ return (x.Text==y.Text && x.Value==y.Valu e);
}
}
May 4 '06 #2
JB <jb*****@gmail. com> wrote:
I've created a generic of type List<T> where T is a custom
class. I need to use the List<T>.Contain s method. I know
I need to implement the IEqualityCompar er but I can't seem
to get the Contains method to execute my Equals code.
What am I doing wrong?


You are reading the docs too fast. The Remarks section of the
Contains method says:

This method determines equality using the default equality
comparer EqualityCompare r.Default for T, the type of
values in the list.

So it doesn't help make the values implement IEqualityCompar er.

If the List<T> class supported using a custom IEqualityCompar er,
it would be specified as a constructor parameter.

Perhaps you could override the Equals method of your object,
though this isn't a particluarly elegant solution, introducing one
of these typecasts generics should help us eliminate, and also
possibly changing the behavior of NameValue objects in
other places (which might be good or bad...)

NameValue
{
public string Text;
public string Value;

public override bool Equals(object otherObject)
{
NameValue other = otherObject as NameValue;
if (other is NameValue && this.Key == other.Key && this.Value ==
other.Value)
return true;
else
return false;
}
}

I don't know what your code is doing but you should probably use
a collection that is designed to work with key-value pairs instead
of building your own key-value thing on top of a collection that
wasn't meant for this.

Hth/Ole N.
May 4 '06 #3
JB
That worked perfect, looks like I was over complicating things, thanks.

JB

May 4 '06 #4

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

Similar topics

6
6662
by: PengYu.UT | last post by:
Hi, Suppose I have a list which contains pointers. I want the pointer got by dereferencing the iterator be a pointer pointing to a const object. But std::list<const T*>::const_iterator doens't give me this capability. So I want std::list<T*>::iterator. However, the container is of type std::list<T*>. How to get std::list<const T*>::iterator?
7
7754
by: Andrew Robinson | last post by:
I have two List<t>. I need to search ListA to see if it contains ListB So: ListA { 1, 2, 3, 4, 5, 6, 7, 8, 9 } Searching ListA with { 4, 5, 6 } would return true and an index of 3. Searching ListA with { 4, 6, 5 } would return false and or an index of -1. Hope my pseudo coding is clear?
1
2211
by: Robert Bravery | last post by:
Hi all, How can I use the contains method to find a partial value in a list eg if I have a list that contains "I love my Dog" "I hate the mouse" and I want to know if the list contains the partial string "Dog" Thanks
6
46188
by: buzzweetman | last post by:
Many times I have a Dictionary<string, SomeTypeand need to get the list of keys out of it as a List<string>, to pass to a another method that expects a List<string>. I often do the following: <BEGIN CODE> List<stringkeyNameList = new List<string>(); foreach (string keyName in this.myDictionary.Keys)
3
2132
by: janzon | last post by:
Hi! Sorry for the bad subject line... Here's what I mean. Suppose we deal with C++ standard integers lists (the type is indifferent). We have a function f, declared as list<intf(int); Now we have an integer list p, say. For each element x in p, we want to repace x with f(x) to get a new, possibly larger, integer list. Note
2
2253
by: per9000 | last post by:
Hi, *background* I want a class containing an int (a list of sets of integer). This should be hidden for the user and he/she should be able to insert his/her favourite data structure so to be a little fancy I thought I'd do a Ctor like this: // this is the "core": private int sets;
9
6998
by: Stephan Steiner | last post by:
Hi I seem to have a bit of trouble understanding one bit of how generics work: In C#, every class automatically derives from object, and inherits a bunch of properties (i.e. ToString()). Thus, (MyClass is object) should always evaluate as true. However, if I have a method with the following signature:
2
5895
by: Assimalyst | last post by:
Hi I have a Dictionary<string, List<string>>, which i have successfully filled. My problem is I need to create a filter expression using all possible permutations of its contents. i.e. the dictionary essentially creates the following array: Key Value
1
8873
by: shapper | last post by:
Hello, On my MVC projects I often create classes which contains properties which are lists of other classes. Should I start using IQueryable<Tor IEnumerable<Tinstead of List<T>? What are the differences and when should I use IQueryable<T>, IEnumerable<Tor List<T>?
0
9566
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
9393
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
10153
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
10007
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
9946
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
9832
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
8830
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
5413
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3530
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.