0

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.

tobsen
  • 5,328
  • 3
  • 34
  • 51
Paladin
  • 1,637
  • 13
  • 28

3 Answers3

3

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 ) );
Panos Theof
  • 1,450
  • 1
  • 21
  • 27
2

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();
Ehsan
  • 31,833
  • 6
  • 56
  • 65
0

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);

nbanic
  • 1,270
  • 1
  • 8
  • 11
Venson
  • 1,772
  • 17
  • 37
  • It should work with Array.Sort as well. See http://stackoverflow.com/questions/5430016/better-way-to-sort-array-in-descending-order – tobsen Aug 04 '13 at 11:40