Skip to main content
GameDev.net gamedev.net
🔒 Locked

c# sorting

Started by TutenStain May 29, 2010 at 4:05 AM 3 replies 850+ views
Original Post
TutenStain
TutenStain
Hello! I have struct that looks like this: public struct DataStruct { public string personnummer; public string namn; public string efternamn; public string telefon; public string email; } DataStruct[] Data = new DataStruct[100]; I would like to print the struct out to a file based on personnummer (personnumber). Like this: 851543 <-- Lower number comes first. Test Hey 0533335 ff@yahgoo.se 920617 John Lock 0500427743 john@yahoo.se Thank you.
Nik02
Nik02
To sort the array using a simple QuickSort algorithm, the Array type has a Sort method which is overloaded with several useful versions.

If the underlying datatype of the array does not implement IComparable (which defines how two instances of that datatype are compared), you can use an overload that takes a custom comparison function.

The following code injects the comparison function directly into the sort method parameter; this is called a "lambda expression". You can give an externally-written function to the method instead, if you prefer - but the lambda style is often more compact especially if you only need the function definition once where you write it.

//IIRC, requires .net 3.0 because of the lambda            Array.Sort(Data, (a, b) =>                {                    if (a.personnummer < b.personnummer) return -1;                    else if (a.personnummer > b.personnummer) return 1;                    else return 0;                });


The Sort method itself handles the swapping of the elements in the array so you don't have to write that part yourself.

If you need more advanced sorting, you need to get your hands dirty on the swapping logic too.

For more info, see MSDN for "Array.Sort method" in the .net framework SDK. The topic predates lambda availability so there is no specific equivalent of the sample code I posted here. However, the overload I used is:

Array.Sort(T) Generic Method (T[], Comparison(T))  
Niko Suni
jods
jods
Side-note: is there a reason you use struct instead of class? Doing so usually results in more harm than good. (Especially if you don't master all the interesting differences between a reference type and a value type.)

Most .NET sorting and comparing APIs take an optional IComparer interface. Look it up.
Or if you don't want to create a distinct class (maybe your records are always sorted that way) you can implement the IComparable interface directly.

If you want a quick one-shot solution you may use LINQ:

foreach (var item in Data.OrderBy(x => x.personnummer))
// print item

Of course using strings to store numbers may not provide the sort order you'd expect.

EDIT: Nik02 wrote an answer at the same time as I did. Interestingly they are somewhat different: Nik02 code actually sorts your array structure (and stores the sorted array). My suggestion doesn't modify your array, it only sorts the items for the display operation.
Also you should realize that neither way is terribly efficient with big structs.
Nik02
Nik02
LINQ is probably better if you don't want to sort the original data but just display it in a defined order. I didn't read the spec carefully enough :)

Anyway, as I implied - quicksort may not be the most efficient algorithm for sorting, depending on your source data. It is good when the elements of the array are in somewhat correct order to begin with and there are relatively few elements; in most other cases, there are better algorithms available. See Wikipedia for ideas if you need them :)
Niko Suni
TutenStain
TutenStain
Thanks for pointing me in the right direction.

By reading your posts I was able to make this:

Array.Sort(Data, (a, b) => String.Compare(a.personnummer, b.personnummer));

Works well :)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.