Sort 2-Dimensional Jagged Array CSharp.

Hi,

I needed to sort a list of a 2-dimensional jagged array of files in MSBuild. The idea being is that I’d have SQL files from different folders. I’d like the files in both folders collected into a single list and then run alphabetically based upon filename not foldername+filename.

 using System; using System.Collections.Generic; using System.IO; using System.Text; using Microsoft.Build.Utilities; using Microsoft.Build.Framework; using System.Diagnostics; using System.Management; using System.Collections;
namespace MySortList
 {
 ///
public class SortList : Task
 {
 private bool _Success = true;
public virtual bool Success
 {
 get
 {
 return _Success;
 }
 set
 {
 _Success = value;
 }
 }
private string[] _SQLFileList;
[Required]
 public virtual string[] SQLFileList
 {
 get
 {
 return _SQLFileList;
 }
 set
 {
 _SQLFileList = value;
 }
 }
private string[] _SortedSQLFileList;
[Output]
 public virtual string[] SortedSQLFileList
 {
 get
 {
 return _SortedSQLFileList;
 }
 set
 {
 _SortedSQLFileList = value;
 }
 }
public override bool Execute()
 {
 string[][] sqlScriptFiles = new string[_SQLFileList.Length][];
for (int x = 0; x < _SQLFileList.Length; x++)
 {
sqlScriptFiles[x] = new string[2];
 //split the filePath to get the filename
 string[] splitFilePath = _SQLFileList[x].Split(new char[] { '\\' });
sqlScriptFiles[x][0] = _SQLFileList[x];
 //get last item in the array
 sqlScriptFiles[x][1] = splitFilePath[splitFilePath.Length - 1];
 }
//sort the script files based upon the second column - note zero based array, hence 1.
 Sort(sqlScriptFiles, 1);
List sortedSqlFiles = new List();
 foreach (string[] sqlFile in sqlScriptFiles)
 {
 sortedSqlFiles.Add(sqlFile[0].ToString());
 }
_SortedSQLFileList = sortedSqlFiles.ToArray();
return _Success;
 }
private static void Sort(T[][] data, int col)
 {
 Comparer comparer = Comparer.Default;
 Array.Sort(data, (x, y) => comparer.Compare(x[col], y[col]));
 }
}
}
Advertisements

About jpadda

Technical Consultant currently working as part of the .Net team for EMC Consulting.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s