Reputation: 141
I am reading sheet names from excel file using interop.excel
. And adding sheet names to string array. I want to sort the strings array manually. Like I have values in string array.
I want to sort it like
Code is under.
Microsoft.Office.Interop.Excel.Application xlApp =
new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkBook =
xlApp.Workbooks.Open(openFileExcel.FileName);
string[] xlSheets = new string[xlWorkBook.Worksheets.Count];
int i = 0;
foreach (Microsoft.Office.Interop.Excel.Worksheet wSheet in xlWorkBook.Worksheets)
{
xlSheets[i] = wSheet.Name;
i++;
}
Upvotes: 0
Views: 68
Reputation: 112362
Assign a number to the two categories of items. ECE
and Nur
=> 0, all the other ones => 1. Then sort by this number first and by the string next.
xlSheets = xlSheets
.OrderBy(s => s == "ECE" || s == "Nur" ? 0 : 1)
.ThenBy(s => s)
.ToArray();
Upvotes: 1
Reputation: 37020
From the comments we've determined that you want to sort by a class numbering system, but it's not clear if that information is available. Please update the question if it is, and we can provide a better answer.
But in the meantime, here's a way to "hard-code" the order, by creating an array of known items in the deisred order, and then using OrderBy
(from System.Linq
) to order the items from excel by their index in the ordered array. Any items that aren't in our "ordered array" are placed at the end in their original order:
// This array contains the desired order of known items
string[] orderedNames =
{
"ECE", "Nur", "G 1", "G 4", "G 6", "G 7",
};
// This array comes from Excel, and is not in the order we desire
string[] xlSheets =
{
"G 7", "G 4", "G 6", "Nur", "G 1", "ECE",
};
// Here we sort by the index of the item in the orderedNames array. Any items
// that aren't in that array are added to the end, in their original order
xlSheets = xlSheets
.OrderBy(name => orderedNames.Contains(name) // If the name is in our ordered array
? Array.IndexOf(orderedNames, name) // Then order by it's index in the array
: orderedNames.Length) // Else use a number greater than the count of known items
.ToArray();
An alternate way to write this is to first OrderByDecending
on whether or not the item is in the array (true
will come first, so items NOT in the array will be last), and ThenBy
their index in the ordered array:
xlSheets = xlSheets
.OrderByDescending(name => orderedNames.Contains(name))
.ThenBy(name => Array.IndexOf(orderedNames, name))
.ToArray();
Notice that in both cases we have to consider whether or not the item is in the array. This is because Array.IndexOf
will return -1
if an item is not found, and that will put the "not found" items before the "found" items, which we don't want.
Upvotes: 1