473,800 Members | 2,404 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

compare a list of integers

Tem
List<inta = new List<int>();
a.Add(1);
a.Add(2);
a.Add(3);

List<intb = new List<int>();
b.Add(1);
b.Add(2);
b.Add(3);

I need to compare two integer lists.
It returns true if values and ordering are the same.
Is there a better way to do this than a foreach loop?

Tem
Jun 27 '08 #1
6 8552
Tem <te*****@yahoo. comwrote:
List<inta = new List<int>();
a.Add(1);
a.Add(2);
a.Add(3);

List<intb = new List<int>();
b.Add(1);
b.Add(2);
b.Add(3);

I need to compare two integer lists.
It returns true if values and ordering are the same.
Is there a better way to do this than a foreach loop?
Which version of .NET are you using? .NET 3.5 has an extension method
on IEnumerable<Tof SequenceEqual:

if (a.SequenceEqua l(b))
....

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Jun 27 '08 #2
Tem
3.5
but I thought extension methods would make things slow? been trying to avoid
them
"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** *************@m snews.microsoft .com...
Tem <te*****@yahoo. comwrote:
>List<inta = new List<int>();
a.Add(1);
a.Add(2);
a.Add(3);

List<intb = new List<int>();
b.Add(1);
b.Add(2);
b.Add(3);

I need to compare two integer lists.
It returns true if values and ordering are the same.
Is there a better way to do this than a foreach loop?

Which version of .NET are you using? .NET 3.5 has an extension method
on IEnumerable<Tof SequenceEqual:

if (a.SequenceEqua l(b))
...

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Jun 27 '08 #3
but I thought extension methods would make things slow? been trying to avoid
them
Why would you think that? OK, in reality you could shave a few cycles
if you know you have List<Tby checking the length first
(SequenceEqual doesn't do this, although this could be a missed
opportunity - it could check if both operands implement IList, and
compare the length) - and because it is using the interface (rather
than direct to the sealed List<T>) it won't inline any of the fetches
- but this is rarely the most significant thing.

My advice: use the simplest code that clearly expresses what you want
to do. SequenceEqual does this; *if* you later find this is a
bottleneck, then tweak it (perhaps introduce a List<TSequenceE qual
extension method) - but until then you're optimising prematurely.

Marc
Jun 27 '08 #4
For reference - an additional overload that checks a few obvious cases
first... just add your namespace as a "using" at the top, and the
overload resolution will select it instead of
Enumerable.Sequ enceEqual, since ICollection<Tis more specific than
IEnumerable<T>

Adding a List<T>-specific version would almost certainly be overkill;
I doubt you'd ever see any tangible performance benefit in most code.

Marc

namespace SomeNamespace
{
public static class CollectionExt
{
public static bool SequenceEqual<T >(this ICollection<Tfi rst,
ICollection<Tse cond)
{
return SequenceEqual<T >(first, second,
EqualityCompare r<T>.Default);
}
public static bool SequenceEqual<T >(this ICollection<Tfi rst,
ICollection<Tse cond, IEqualityCompar er<Tcomparer)
{
if (first == null) throw new
ArgumentNullExc eption("first") ;
if (second == null) throw new
ArgumentNullExc eption("second" );
if (ReferenceEqual s(first, second)) return true;
if (first.Count != second.Count) return false;
return System.Linq.Enu merable.Sequenc eEqual<T>(first ,
second, comparer);
}
}
}
Jun 27 '08 #5
Tem
Thanks Marc

Something tells me this will be much more efficient.

"Marc Gravell" <ma**********@g mail.comwrote in message
news:98******** *************** ***********@24g 2000hsh.googleg roups.com...
For reference - an additional overload that checks a few obvious cases
first... just add your namespace as a "using" at the top, and the
overload resolution will select it instead of
Enumerable.Sequ enceEqual, since ICollection<Tis more specific than
IEnumerable<T>

Adding a List<T>-specific version would almost certainly be overkill;
I doubt you'd ever see any tangible performance benefit in most code.

Marc

namespace SomeNamespace
{
public static class CollectionExt
{
public static bool SequenceEqual<T >(this ICollection<Tfi rst,
ICollection<Tse cond)
{
return SequenceEqual<T >(first, second,
EqualityCompare r<T>.Default);
}
public static bool SequenceEqual<T >(this ICollection<Tfi rst,
ICollection<Tse cond, IEqualityCompar er<Tcomparer)
{
if (first == null) throw new
ArgumentNullExc eption("first") ;
if (second == null) throw new
ArgumentNullExc eption("second" );
if (ReferenceEqual s(first, second)) return true;
if (first.Count != second.Count) return false;
return System.Linq.Enu merable.Sequenc eEqual<T>(first ,
second, comparer);
}
}
}
Jun 27 '08 #6
Tem <te*****@yahoo. comwrote:
Something tells me this will be much more efficient.
Certainly in the special cases, where the two lists are either
"obviously" different or "obviously" the same.

But note that it's still an extension method - your earlier comment
about how you've been "trying to avoid [extension methods]" should be
reconsidered, IMO.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Jun 27 '08 #7

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

Similar topics

30
3493
by: Christian Seberino | last post by:
How does Ruby compare to Python?? How good is DESIGN of Ruby compared to Python? Python's design is godly. I'm wondering if Ruby's is godly too. I've heard it has solid OOP design but then I've also heard there are lots of weird ways to do some things kinda like Perl which is bad for me. Any other ideas?
8
2673
by: peashoe | last post by:
I have an asp page that uses a calendar.js (pop-up) file to add an exact date format in the text field (txtDDate). My problem is I need some javascript that sets an alert that does not allow them to select today. example: var dtToday = Date() if(document.frmSoftware.txtDDate.value == dtToday) {
4
7027
by: slot | last post by:
Is it possible to compare "enum" types to basic types like "unsigned short" type at all? Thanks!
49
14915
by: raju | last post by:
hi can we compare two integers without using relational operators (== != < <= > >=) thanks rajesh s
7
12897
by: Prabhudhas Peter | last post by:
I have two object instances of a same class... and i assigned values in both object instances (or the values can be taken from databse and assigned to the members of the objects)... Now i want to compare these two objects so that it will return true if both object's members have the same value... it is good if u can give me a single function or simple code snippet.. Thank U -- Peter...
2
2577
by: Stevie | last post by:
Hello I'm trying to work out the regular expression for carrying out a simple 'greater than' comparison. I have a directory with files such as asd345.log, asd346.log, asd347.log and so on.
7
12724
by: Girish Sahani | last post by:
Hi, Please check out the following loop,here indexList1 and indexList2 are a list of numbers. for index1 in indexList1: for index2 in indexList2: if ti1 == ti2 and not index1 != indexList1.pop(): index1+=1 index2+=1 continue
11
17820
by: balakrishnan.dinesh | last post by:
hi frnds, Im having two 20digit numbers, But while comparing those it is giiving wrong ouput in javascript. for example here is my code, my secanrio is , ~ If first 20 digit number is greater number than second 20 digit number ,then it should return.
6
4020
by: Amit Bhatia | last post by:
Hi, I am not sure if this belongs to this group. Anyway, my question is as follows: I have a list (STL list) whose elements are pairs of integers (STL pairs, say objects of class T). When I create a new object of class T, I would like to check if this object already exists in the list: meaning one having same integers. This can be done in linear time in a list, and probably faster if I use STL Set instead of list. I am wondering however if...
0
9690
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
9551
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
10505
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
10275
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
10033
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...
1
7576
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
6811
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
5471
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...
0
5606
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.