[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 739
  • Last Modified:

IComparer for IP Addresses

I have a Component One C1FlexGrid with a column that contains IP addresses (a.b.c.d). I'd like to sort the IP addresses properly. Currently the sort looks like this:

10.0.0.100
10.0.0.11
10.0.0.135
10.0.0.2
239.255.255.1
64.74.98.81

The order should be:
10.0.0.2
10.0.0.11
10.0.0.100
10.0.0.135
64.74.98.81
239.255.255.1

The C1FlexGrid takes an IComparer for sorting the column data. How do I write the comparer?
I'm using C# in Visual Studio 2005.
0
goondoo27
Asked:
goondoo27
  • 2
1 Solution
 
Roshan DavisCommented:
will be something like this. You may need to optimize or add some conditions to it. It was my fast writing code :)
class CompareIP : IComparer 
{ 
	// Implement the IComparable interface. 
	public int Compare(object obj1, object obj2) 
	{ 
		string str1, str2; 
		str1 = obj1 as string; 
		str2 = obj2 as string; 

		string []ipAr1 = str1.Split('.');
		string []ipAr2 = str2.Split('.');

		int idx = 0;
		foreach(string str in ipAr1)
		{
			int val1 = int.Parse(str);
			int val2 = int.Parse(ipAr2[idx]);

			if (val1 != val2)
			{
				return (val1 - val2);
			}
			idx++;
		}

		return 0;
	} 
}

Open in new window

0
 
goondoo27Author Commented:
Thanks for the quick response. I'll try to integrate it this weekend.
0
 
goondoo27Author Commented:
Ok that was much easier than I thought. It worked great. I've attached the actual modified code.
class CompareIP : IComparer
{
	C1FlexGrid _flex;
	bool _desc;		// Descending sort order

	// Constructor
	public CompareIP(C1FlexGrid flex, SortFlags order)
	{
		_flex = flex;
		_desc = ((order & SortFlags.Descending) != 0);
	}

	// IComparer
	public int Compare(object obj1, object obj2)
	{
		string ip1 = (string) _flex[((Row)obj1).Index, "ip"];
		string ip2 = (string) _flex[((Row)obj2).Index, "ip"];

		if(string.IsNullOrEmpty(ip1) || string.IsNullOrEmpty(ip2))
			return 0;

		string[] ipAr1 = ip1.Split('.');
		string[] ipAr2 = ip2.Split('.');

		int idx = 0;
		foreach(string str in ipAr1)
		{
			int val1 = int.Parse(str);
			int val2 = int.Parse(ipAr2[idx]);

			if(val1 != val2)
			{
				return (val1 - val2);
			}
			idx++;
		}

		return 0;
	}
}

Open in new window

0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now