0

给定以下数据类型

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

我有这样的事情:

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

问题:如何按“headercode”字段排序?

FileDefinition[] filedefs = clsFiledefs.getFileDefinitions();
FileDefinition[] filedefs2 = SOMEMAGIC(filedefs);

我需要它来让我的数组按最长字段排序到最短。

我试过了Array.Sort(X,y),但是没有用。提前感谢所有答案。

4

3 回答 3

3

使用以下内容:

Array.Sort( filedefs, ( a, b ) => a.headercode.Length.CompareTo( b.headercode.Length ) );

如果您不想更改原始数组,那么

FileDefinition[] filedefs2 = (FileDefinition[])filedefs.Clone();
Array.Sort( filedefs2, ( a, b ) => a.headercode.Length.CompareTo( b.headercode.Length ) );
于 2013-08-04T11:52:13.303 回答
2

你可以这样做

var sorted = filedefs.OrderBy(x=> x.headercode, StringComparer.InvariantCultureIgnoreCase).ToArray();
var sorted = filedefs.OrderByDescending(x=> x.headercode, StringComparer.InvariantCultureIgnoreCase).ToArray();

如果您想按长度订购

var sorted = filedefs.OrderBy(x=> x.headercode.Length).ToArray();
var sorted = filedefs.OrderByDescending(x=> x.headercode.Length).ToArray();
于 2013-08-04T11:46:25.103 回答
0

您应该使用 a List<FileDefinition>(因为将项目添加到列表中就像添加到数组中一样容易得多),而不仅仅是使用Linq表达式OrderBy对列表进行排序。

knownfiles.OrderBy(s => s.readNumBytes);

于 2013-08-04T11:36:03.983 回答