?
Solved

Ignoring first X characters from an array when sorting.

Posted on 2010-11-11
4
Medium Priority
?
389 Views
Last Modified: 2013-12-17
I have an array of roughly 5000 elements, each of which is in this format:

"\\\\192.168.5.6\\log\\freeswitch.log.2010-06-20-18-54-29.1"      string
AND
"\\\\192.168.5.8\\log\\freeswitch.log.2010-08-03-20-09-40.1"      string

I need to sort this array by the dates, not by the server address. How would I go about making it so that the Array.Sort() method ignores all characters prior to "log"? From what I can see, I need to implement an IComparer interface, I'm just not too sure how.

0
Comment
Question by:Kilsol
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 33

Accepted Solution

by:
Todd Gerbert earned 1000 total points
ID: 34115488
Here's a simple example, this skips the first 4 chars
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
	class Program
	{
		static void Main(string[] args)
		{
			string[] strings = { "bbb.log.1", "aaa.log.2", "ddd.log.3", "ccc.log.4" };

			Console.WriteLine("Normal sort:");
			Array.Sort(strings);
			foreach (string s in strings)
				Console.WriteLine(s);

			// Reset array
			strings = new string[] { "bbb.log.1", "aaa.log.2", "ddd.log.3", "ccc.log.4" };
			Console.WriteLine("\r\nCustom sort:");
			Array.Sort(strings, new SkipFirstNCharComparer(3));
			foreach (string s in strings)
				Console.WriteLine(s);

			Console.ReadKey();
		}
	}

	public class SkipFirstNCharComparer : IComparer
	{
		private int _charsToSkip;
		public SkipFirstNCharComparer(int numCharsToSkip)
		{
			_charsToSkip = numCharsToSkip;
		}
		public int Compare(object x, object y)
		{
			int maxLen = ((string)x).Length > ((string)y).Length ? ((string)x).Length : ((string)y).Length;
			return String.CompareOrdinal((string)x, _charsToSkip, (string)y, _charsToSkip, maxLen);
		}
	}
}

Open in new window

0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 34117283
If you want to compare based on the DATES then you need to extract those portions and convert them to Dates so you can do that comparison...

...something like:
private void button1_Click(object sender, EventArgs e)
        {
            string[] data = {"\\\\192.168.5.8\\log\\freeswitch.log.2010-08-03-20-09-40.1", "\\\\192.168.5.6\\log\\freeswitch.log.2010-06-20-18-54-29.1"};
            Array.Sort(data, MyComparer);
        }

        private int MyComparer(string a, string b)
        {
            string[] aVals = a.Split(".".ToCharArray());
            string[] bVals = b.Split(".".ToCharArray());
            int aIndex = Array.IndexOf(aVals, "log");
            int bIndex = Array.IndexOf(bVals, "log");
            if (aIndex != -1 && (aIndex + 1) < aVals.Length && bIndex != -1 && (bIndex + 1) < bVals.Length)
            {
                string dtFormat = "yyyy-MM-dd-HH-mm-ss";
                DateTime aDT, bDT;
                if (DateTime.TryParseExact(aVals[aIndex + 1], dtFormat, null, System.Globalization.DateTimeStyles.None, out aDT))
                {
                    if (DateTime.TryParseExact(bVals[bIndex + 1], dtFormat, null, System.Globalization.DateTimeStyles.None, out bDT))
                    {
                        return aDT.CompareTo(bDT); // sort based on date values
                    }
                }
            }
            return a.CompareTo(b); // something was wrong with formatting; revert to string comparison
        }

Open in new window

0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 34117448
*Note that the code in tgerbert's example works because the dates have been formatted with leading zeroes, military time has been used, and the order of the values lends itself to a straight STRING comparison.  If the order and format of the dates was different it probably wouldn't work...just keep that in mind if the format changes or you need to do a similar thing with a different project.

My code is actually converting the "date/time" strings to DateTime instances using the specified format so they can be compared correctly as DateTimes instead of as strings.
0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 34117780
I  should also point out my example also assumes it's safe to just ignore the first n characters, if one of the filenames happens to start with an IP address with more chars that logic breaks.

0

Featured Post

Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
Suggested Courses

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question