Re: Beginner question re data structure
- From: Larry Lard <larrylard@xxxxxxxxxxxxxx>
- Date: Fri, 18 Aug 2006 11:56:56 +0100
gc wrote:
Hello all,
I'm working on a console app that takes as input a list of domain names
then pings them. The data I want to work with is:
long rtt (ping round trip time in ms)
IPAddress ip
string hostName
Right now the app just prints the info in the order it's placed on the
command line.
What I want to do is store this information, then sort all the results
by rtt for display. (Lowest rtt first.)
I thought of adding an object that I could do something like add each
result (rtt, ip, hostName). The object could have a method to sort
itself and a tostring.
You're there already!
My problem is, how to represent the data structure rtt, ip, hostName?
Well, we could *almost* use System.Net.PingReply, except that you want to store the host *name* as well. I would say:
Put each result in a class:
class PingResult
{
// of course wrap these in properties in the real world...
public long RoundTripTime;
public IPAddress Address;
public string Hostname;
}
Now we want somewhere to put these. Your later post clarified that you are using C# 2.0, so we have the lovely generic containers available. One of these is List<>, which has a Sort method. But it will need to know how to sort the things we put in it. An easy way to do this is to have PingResult implement IComparable<>, so we add that to the definition:
class PingResult : IComparable<PingResult>
{
long RoundTripTime;
IPAddress Address;
string Hostname;
public int CompareTo(PingResult other)
{
if (other != null)
return this.RoundTripTime.CompareTo(other.RoundTripTime);
else
return 1;
}
}
Our comparison routine just defers to long's comparison.
Now when we obtain each ping result, we put a new PingResult in our collection:
List<PingResult> results = new List<PingResult>();
for (int i = 0; i < 10; ++i)
{
// get a result somehow
PingResult result = GetAPingResult();
// put it in the list
results.Add(result);
}
// sort the list
results.Sort();
// now the list is in order of RoundTripTime
The Sort method will see that PingResult implements IComparable<>, and so it will use that for sorting on.
--
Larry Lard
larrylard@xxxxxxxxxxxxxx
The address is real, but unread - please reply to the group
For VB and C# questions - tell us which version
.
- Follow-Ups:
- References:
- Beginner question re data structure
- From: gc
- Beginner question re data structure
- Prev by Date: Re: Test for empty Dataset field
- Next by Date: Re: Urgent - How to access all radiobuttonlists in a loop (c# asp.net)
- Previous by thread: Re: Beginner question re data structure
- Next by thread: Re: Beginner question re data structure
- Index(es):
Relevant Pages
|