473,626 Members | 3,427 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Array.Sort a struct

Hello,

Is it possible to sort an array with a struct in it?

example:

I have a struct:
public struct mp3file
{
public int tracknr;
public int length;
public string filename;
public string artist;
public string title;
}

and than I have this:

mp3file[] mp3 = new mp3file[files.Length];
int t = 0;

foreach (FileInfo fi in files)
{
MP3File mp3File = ShellID3TagRead er.ReadID3Tags( fi.FullName);
mp3[t].length = mp3File.Length;
mp3[t].artist = mp3File.ArtistN ame;
mp3[t].title = mp3File.SongTit le;
mp3[t].tracknr = mp3File.TrackNu mber;
mp3[t].filename = mp3File.FileNam e;
t++;
}

this is working, but now I want to sort the array by tracknr, so I can make
a playlist, sorted by tracknr.
with something like:

Array.Sort(mp3. tracknr)

but that doesn't work

How can I do this?

Thanks for your help!
--

www.gsnel.nl
Feb 3 '06 #1
16 16385
Gerrit <gs************ *@hotmail.com> wrote:
Is it possible to sort an array with a struct in it?

example:

I have a struct:
public struct mp3file
{
public int tracknr;
public int length;
public string filename;
public string artist;
public string title;
}
Why is this a struct? That seems like a bad idea to me. (I'd also
suggest that you don't have public fields, by the way.)
and than I have this:
<snip>
this is working, but now I want to sort the array by tracknr, so I can make
a playlist, sorted by tracknr.
with something like:

Array.Sort(mp3. tracknr)

but that doesn't work

How can I do this?


You still want to sort the array, so you need to call Array.Sort with
mp3 as one parameter - but there's an overload which takes an IComparer
(or one which takes an IComparer<T> if you're using .NET 2.0) which is
used for the sorting. You need to implement IComparer in some class or
other to descibe the ordering you want.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 3 '06 #2

"Gerrit" <gs************ *@hotmail.com> wrote in message
news:S0REf.4732 $zc1.1422@amstw ist00...
Hello,

Is it possible to sort an array with a struct in it?

example:

I have a struct:
public struct mp3file
{
public int tracknr;
public int length;
public string filename;
public string artist;
public string title;
}

and than I have this:

mp3file[] mp3 = new mp3file[files.Length];
int t = 0;

foreach (FileInfo fi in files)
{
MP3File mp3File = ShellID3TagRead er.ReadID3Tags( fi.FullName);
mp3[t].length = mp3File.Length;
mp3[t].artist = mp3File.ArtistN ame;
mp3[t].title = mp3File.SongTit le;
mp3[t].tracknr = mp3File.TrackNu mber;
mp3[t].filename = mp3File.FileNam e;
t++;
}

this is working, but now I want to sort the array by tracknr, so I can
make a playlist, sorted by tracknr.
with something like:

Array.Sort(mp3. tracknr)

but that doesn't work

How can I do this?

Thanks for your help!
--

www.gsnel.nl


You'd have to create an IComparer class. The following *should* be what you
need :)

public struct mp3file
{
public int tracknr;
public int length;
public string filename;
public string artist;
public string title;
}

public class Class1
{

public Class1() { }

public void Mp3Files()
{
mp3file[] files = new mp3file[2];
files[0].tracknr = 2;
files[0].length = 5000;
files[0].filename = "blah2";
files[0].title = "Title 2";
files[1].tracknr = 1;
files[1].length = 5000;
files[1].filename = "blah1";
files[1].title = "Title 1";
Array.Sort(file s, new Mp3FileComparer ());

foreach (mp3file file in files) {
Console.WriteLi ne(file.tracknr );
}
}
}

public class Mp3FileComparer : System.Collecti ons.IComparer
{
public Mp3FileComparer () { }

public int Compare(object Object1, object Object2)
{
if (!(Object1 is mp3file)) {
throw new ArgumentExcepti on(
"Object1 must be of type mp3file.",
"Object1"
);
} else if (!(Object2 is mp3file)) {
throw new ArgumentExcepti on(
"Object2 must be of type mp3file.",
"Object2"
);
}

int n1 = ((mp3file) Object1).trackn r;
int n2 = ((mp3file) Object2).trackn r;

if (n1 > n2) {
return 1;
} else if (n1 == n2) {
return 0;
} else {
return -1;
}
}
}
HTH :)

Mythran

Feb 3 '06 #3
You still want to sort the array, so you need to call Array.Sort with
mp3 as one parameter - but there's an overload which takes an IComparer
(or one which takes an IComparer<T> if you're using .NET 2.0) which is
used for the sorting. You need to implement IComparer in some class or
other to descibe the ordering you want.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too


And to extend on what Jon was stating...the following is v1.1 code and uses
the IComparable interface instead of the IComparer interface. The MP3File
class implements this interface and containts the implementation of
CompareTo, which is all Array.Sort method needs to sort the class (notice,
it is no longer just a struct, but a full class w/o comments).

public class MP3File : IComparable
{

#region Private Members
// =============== =============== =============== =============== =====
// Private Members
// =============== =============== =============== =============== =====

private int mTrackNumber;
private int mLength;
private string mFileName;
private string mArtist;
private string mTitle;
#endregion

#region Constructors / Destructors
// =============== =============== =============== =============== =====
// Constructors / Destructors
// =============== =============== =============== =============== =====

public MP3File() { }
#endregion

#region Public Properties
// =============== =============== =============== =============== =====
// Public Properties
// =============== =============== =============== =============== =====

public int TrackNumber
{
get { return mTrackNumber; }
set { mTrackNumber = value; }
}

public int Length
{
get { return mLength; }
set { mLength = value; }
}

public string FileName
{
get { return mFileName; }
set { mFileName = value; }
}

public string Artist
{
get { return mArtist; }
set { mArtist = value; }
}

public string Title
{
get { return mTitle; }
set { mTitle = value; }
}
#endregion

#region Public Methods
// =============== =============== =============== =============== =====
// Public Methods
// =============== =============== =============== =============== =====

public int CompareTo(objec t obj)
{
if (!(obj is MP3File)) {
throw new ArgumentExcepti on(
"Argument 'obj' is not of type MP3File.",
"obj"
);
}

int num = ((MP3File) obj).TrackNumbe r;
if (this.TrackNumb er < num) {
return -1;
} else if (this.TrackNumb er == num) {
return 0;
} else {
return 1;
}
}

public override string ToString()
{
return string.Format(
"{0} : {1} : {2}",
this.TrackNumbe r,
this.Artist,
this.Title
);
}
#endregion

}

/// The following class should be created and the Mp3Files method called to
/// test the functionality of the MP3File and IComparable.
public class Class1
{

public Class1() { }

public void Mp3Files()
{
MP3File[] files = new MP3File[3];

files[0] = new MP3File();
files[0].TrackNumber = 3;
files[0].Length = 5000;
files[0].Artist = "Me";
files[0].FileName = "MyFileName 3";
files[0].Title = "Title 3";

files[1] = new MP3File();
files[1].TrackNumber = 1;
files[1].Length = 23422;
files[1].Artist = "My";
files[1].FileName = "MyFileName 1";
files[1].Title = "Title 1";

files[2] = new MP3File();
files[2].TrackNumber = 2;
files[2].Length = 23421;
files[2].Artist = "Mine";
files[2].FileName = "MyFileName 2";
files[2].Title = "Title 2";

Array.Sort(file s);

foreach (MP3File file in files) {
Console.WriteLi ne(file);
}
}
}

:)

HTH some more.

Mythran

Feb 3 '06 #4
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** @msnews.microso ft.com...
Gerrit <gs************ *@hotmail.com> wrote:
Is it possible to sort an array with a struct in it?

example:

I have a struct:
public struct mp3file
{
public int tracknr;
public int length;
public string filename;
public string artist;
public string title;
}


Why is this a struct? That seems like a bad idea to me. (I'd also
suggest that you don't have public fields, by the way.)


Why is it being a struct a bad idea? I just read the "Structs Tutorial" on
MSDN and it said "Whenever you have a need for a type that will be used
often and is mostly just a piece of data, structs might be a good option."
It looks like all data to me, so if you could clear up what's bad about it,
that'd be great.
Feb 4 '06 #5

"James Park" <so*****@hotmai l.com> wrote in message
news:%2******** **********@TK2M SFTNGP09.phx.gb l...
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** @msnews.microso ft.com...
Gerrit <gs************ *@hotmail.com> wrote:
Is it possible to sort an array with a struct in it?

example:

I have a struct:
public struct mp3file
{
public int tracknr;
public int length;
public string filename;
public string artist;
public string title;
}


Why is this a struct? That seems like a bad idea to me. (I'd also
suggest that you don't have public fields, by the way.)


Why is it being a struct a bad idea? I just read the "Structs Tutorial" on MSDN and it said
"Whenever you have a need for a type that will be used often and is mostly just a piece of data,
structs might be a good option." It looks like all data to me, so if you could clear up what's bad
about it, that'd be great.


Hi James,

// First C++
If you pass a struct to a function it will be copied (value semantics). If you want reference
semantics, you pass in a pointer or a reference.

Now C#
structs in C# act ALOT like C++ structs. If you pass it into a function you will get a copy of the
struct and not the original struct. This is where C# Classes come in. You NEVER deal directly with
an object, You ALWAYS deal with a reference to the object. Unlike C++ reference, which cannot be
reassigned, C# references are more like auto dereferenced pointers.

So, why is it a bad idea in your case???
Passing your struct to a function is more expensive than passing the same data as a class, since the
struct has to be totally copied whereas only the reference to the class needs to be copied. Granted,
your struct is not huge, but it will still be slower (like that Sort you were asking about).

There are other subtle gotchas as well.
Take the following code.
----------------------------------
Thing myThing = new Thing(/*blah*/);
Foo(myThing );

public void Foo(Thing thing)
{
thing.X = 3;
}
---------------------------------
Will myThing be modified??
YES:If it is a class
NO : If it is a struct

Most C# programmers will expect the code to work (Assume it is a class)
Without looking at the declaration of your struct it is hard to tell that it is not a class.
Subtle bugs are the result.

If you are using struct over class as an optimization... .DON'T.
Test it for yourself if you don't believe us.
Classes are almost always the right way to go

There ARE good uses of struct in C#, but in general, you should use classes.
In C# structs are kind of like gotos
Both can be useful in certain optimization situations, but I would REALLY think twice before using
one without a very good reason.

Bill






Feb 4 '06 #6
"Bill Butler" <qw****@asdf.co m> wrote in message
news:MmWEf.674$ Zy3.238@trndny0 8...

"James Park" <so*****@hotmai l.com> wrote in message
news:%2******** **********@TK2M SFTNGP09.phx.gb l...
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** @msnews.microso ft.com...
Gerrit <gs************ *@hotmail.com> wrote:
Is it possible to sort an array with a struct in it?

example:

I have a struct:
public struct mp3file
{
public int tracknr;
public int length;
public string filename;
public string artist;
public string title;
}

Why is this a struct? That seems like a bad idea to me. (I'd also
suggest that you don't have public fields, by the way.)
Why is it being a struct a bad idea? I just read the "Structs Tutorial"
on MSDN and it said "Whenever you have a need for a type that will be
used often and is mostly just a piece of data, structs might be a good
option." It looks like all data to me, so if you could clear up what's
bad about it, that'd be great.


Hi James,


Hi Bill
So, why is it a bad idea in your case???
I'm not the OP, but that's okay. :)
Passing your struct to a function is more expensive than passing the same
data as a class, since the struct has to be totally copied whereas only
the reference to the class needs to be copied. Granted, your struct is not
huge, but it will still be slower (like that Sort you were asking about).
I ran some Stopwatch tests on Mythran's code.
As written (sample size 200,000):
structs: 2998 milliseconds
classes: 368 milliseconds <-- winner

Modified to use generics (sample size 2,000,000):
structs: 1508 milliseconds <-- winner
classes: 2213 milliseconds

I'm not savvy enough to speculate why the performance balance shifts, but it
indeed does.
There are other subtle gotchas as well.
Take the following code.
----------------------------------
Thing myThing = new Thing(/*blah*/);
Foo(myThing );

public void Foo(Thing thing)
{
thing.X = 3;
}
---------------------------------
Will myThing be modified??
YES:If it is a class
NO : If it is a struct

Most C# programmers will expect the code to work (Assume it is a class)
Without looking at the declaration of your struct it is hard to tell that
it is not a class.
Subtle bugs are the result.
I wouldn't think this would be such a problem, but then again I don't have a
good feel for how frequently that misunderstandin g would occur or how much
time would be wasted on it.
If you are using struct over class as an optimization... .DON'T.
Test it for yourself if you don't believe us.
Classes are almost always the right way to go

There ARE good uses of struct in C#, but in general, you should use
classes.
In C# structs are kind of like gotos
Both can be useful in certain optimization situations, but I would REALLY
think twice before using one without a very good reason.


Personally, I only use structs for P/Invoke stuff, but I'd like to know
other situations where they should be used. It just seemed to me that this
could be a legitimate situation.
Feb 4 '06 #7
James Park <so*****@hotmai l.com> wrote:
Why is this a struct? That seems like a bad idea to me. (I'd also
suggest that you don't have public fields, by the way.)


Why is it being a struct a bad idea? I just read the "Structs Tutorial" on
MSDN and it said "Whenever you have a need for a type that will be used
often and is mostly just a piece of data, structs might be a good option."
It looks like all data to me, so if you could clear up what's bad about it,
that'd be great.


That's just a bad article, unfortunately. It's incorrect in terms of
heap vs stack, too - see http://www.pobox.com/~skeet/csharp/memory.html

Whether you want to use a struct or a class has nothing to with whether
it's "just a piece of data". See my reply on the thread "Structure v/s
classes" for more information.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 4 '06 #8
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
James Park <so*****@hotmai l.com> wrote:
> Why is this a struct? That seems like a bad idea to me. (I'd also
> suggest that you don't have public fields, by the way.)
Why is it being a struct a bad idea? I just read the "Structs Tutorial"
on
MSDN and it said "Whenever you have a need for a type that will be used
often and is mostly just a piece of data, structs might be a good
option."
It looks like all data to me, so if you could clear up what's bad about
it,
that'd be great.


That's just a bad article, unfortunately. It's incorrect in terms of
heap vs stack, too - see http://www.pobox.com/~skeet/csharp/memory.html


Good to know. By the way, my browser is cutting the code examples in your
article off on the right side, but it may be because I'm using the IE7 beta.
Whether you want to use a struct or a class has nothing to with whether
it's "just a piece of data". See my reply on the thread "Structure v/s
classes" for more information.


Here's my take.
1) It looks like the type is atomic (assuming my interpretation of the
word's definition is right).
2) It doesn't look like a lot of data needs to be stored.
3) Depending on how the type is used, it may or may not need to be mutable.

Hmm, it still looks like a struct could be used. Maybe I could use some more
clarification.
Feb 4 '06 #9
James Park <so*****@hotmai l.com> wrote:
That's just a bad article, unfortunately. It's incorrect in terms of
heap vs stack, too - see http://www.pobox.com/~skeet/csharp/memory.html
Good to know. By the way, my browser is cutting the code examples in your
article off on the right side, but it may be because I'm using the IE7 beta.


Wow, that's odd - the examples are pretty narrow. Could you mail me a
screenshot? (sk***@pobox.co m)
Whether you want to use a struct or a class has nothing to with whether
it's "just a piece of data". See my reply on the thread "Structure v/s
classes" for more information.


Here's my take.
1) It looks like the type is atomic (assuming my interpretation of the
word's definition is right).


It's not really - it makes sense to modify each of the fields
individually. It's a collection of data about something.
2) It doesn't look like a lot of data needs to be stored.
There are 2 ints and 3 references, which means 20 bytes on x86 or 28
bytes on x64. Now performance isn't really an issue most of the time,
but it means that any time an mp3file is passed to a method, it's got
to copy all 20 or 28 bytes into the parameter (and likewise if one is
returned). That's like having 5 or 7 reference type parameters.

When it comes to sorting the array, that's going to be slower than
sorting it if mp3file were a reference type - then only the references
would need to be shuffled around, instead of of all the data.
3) Depending on how the type is used, it may or may not need to be mutable.

Hmm, it still looks like a struct could be used. Maybe I could use some more
clarification.


Well a struct *could* be used - but it feels like the wrong decision to
me. I don't see any reason why value type semantics would be desired in
this case.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 4 '06 #10

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

Similar topics

7
25165
by: ritchie | last post by:
Hi all, I am new to this group and I have question that you may be able to help me with. I am trying to learn C but am currently stuck on this. First of all, I have a function for each sort (Bubble, insertion, selection..). I have an array of int's and am passing them to each sort function.
3
7145
by: b83503104 | last post by:
In matlab, the sort function returns two things: =sort() a = 5 7 8 b = 1 3 2 where a is the sorted result, and b is the corresponding index. Is there C or C++ code available to achieve this? Thanks
36
4414
by: Eric Laberge | last post by:
Hi! I'm working on automatically generated code, and need to assign arrays. memcpy is an obvious solution, but it becomes complicated to use in the context I'm working on, ie.: I could use it but I don't want to. Arrays cannot be assigned in C, but structs can, so I coded the following: #include <stdlib.h>
11
2622
by: Cliff Martin | last post by:
Hi, I am reading a fairly large file a line at a time, doing some processing, and filtering out bits of the line. I am storing the interesting information in a struct and then printing it out. This works without any problems. I now would like to filter "duplicate" records. They aren't really duplicate, I can't just qsort as is and eliminate the matching rows. I have number of fields that will be the same, but some of the fields will...
2
3787
by: vikerneso | last post by:
I'm trying to sort an array of structs. My code looks something like this: struct Foo { int number; }; int main() {
4
5222
by: Santosh Nayak | last post by:
Hi, Is it possible to sort the array of struct based on the data members. e.g. struct { int a ; float b ; char c ; } TEMP ;
2
2537
by: Santosh Nayak | last post by:
Hi, Is it possible to sort the array of struct based on the data members. e.g. struct { int a ; float b ; char c ; } TEMP ;
5
3195
by: tienlx | last post by:
Hi all, I want to sort an array of struct _line: .... typedef struct _line { int x1; int x2; } line;
36
2885
by: pereges | last post by:
Hi, I am wondering which of the two data structures (link list or array) would be better in my situation. I have to create a list of rays for my ray tracing program. the data structure of ray looks like this: typedef struct { vector origin; /* vector is an array of 3 doubles */
0
8713
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...
1
8370
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
8514
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
7206
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
6126
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
5579
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
4094
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
1817
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1516
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.