简体   繁体   中英

Sort an array in C#

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.

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM