Reputation: 1637
Given the following Datatype
public class FileDefinition
{
public String headercode;
public String text;
public String fileext;
public int readNumBytes;
public FileDefinition(String headercode, String fileext, String text, int readNumBytes)
{
this.headercode = headercode;
this.fileext = fileext;
this.text = text;
this.readNumBytes = readNumBytes;
}
}
I have something like this:
knownfiles[90] = new FileDefinition(
"^2E524543",
"ivr",
"RealPlayer video file (V11 and later)",
DEFAULT_READ_BYTES
);
knownfiles[89] = new FileDefinition(
"^.{2,4}2D6C68",
"lha",
"Compressed archive file",
DEFAULT_READ_BYTES
);
knownfiles[88] = new FileDefinition(
"^2A2A2A2020496E7374616C6C6174696F6E205374617274656420",
"log",
"Symantec Wise Installer log file",
DEFAULT_READ_BYTES
);
Question: How do i sort by the "headercode" field?
FileDefinition[] filedefs = clsFiledefs.getFileDefinitions();
FileDefinition[] filedefs2 = SOMEMAGIC(filedefs);
I need it to get my array ordered by the longest field to the shortest.
I have tried to Array.Sort(X,y)
, but that did not work.
Thanks in advance for all answers.
Upvotes: 0
Views: 310
Reputation: 1870
You should use a List<FileDefinition>
(Because it's a lot easier to add items into a List as into an array) and than just use the Linq
expression OrderBy
to order your list.
knownfiles.OrderBy(s => s.readNumBytes);
Upvotes: 0
Reputation: 32651
You can do this
var sorted = filedefs.OrderBy(x=> x.headercode, StringComparer.InvariantCultureIgnoreCase).ToArray();
var sorted = filedefs.OrderByDescending(x=> x.headercode, StringComparer.InvariantCultureIgnoreCase).ToArray();
if you want to order by their length
var sorted = filedefs.OrderBy(x=> x.headercode.Length).ToArray();
var sorted = filedefs.OrderByDescending(x=> x.headercode.Length).ToArray();
Upvotes: 2
Reputation: 1470
Use the following:
Array.Sort( filedefs, ( a, b ) => a.headercode.Length.CompareTo( b.headercode.Length ) );
if you don't want to alter the original array then
FileDefinition[] filedefs2 = (FileDefinition[])filedefs.Clone();
Array.Sort( filedefs2, ( a, b ) => a.headercode.Length.CompareTo( b.headercode.Length ) );
Upvotes: 3