Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c# - How would I sort through an array of structs?

I have a struct containing song data:

public struct uLib
    {
        public string Path;
        public string Artist;
        public string Title;
        public string Album;
        public string Length;
    }  

My library consists of an array of this uLib. How would I sort this array by say Artist? Is there a native sort function I can call on this type of array, or will I have to "roll my own"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all, that should not be a struct. It's larger than 16 bytes, so you don't get the performance benefits of having a struct. Also, it doesn't represent a single value, so it doesn't make sense semantically to make it a struct. Just make it a class instead.

The Array class has a Sort method that you can use:

Array.Sort(theArray, (x,y) => string.Compare(x.Artist,y.Artist));

If you don't have C# 3 you use a delegate instead of the lambda expression:

Array.Sort(theArray, delegate(uLib x, uLib y) { return string.Compare(x.Artist,y.Artist) } );

Edit:
Here's an example of what your data could look like as a class:

public class ULib {

    private string _path, _artist, _title, _album, _length;

    public string Path { get { return _path; } set { _path = value; } }
    public string Artist { get { return _artist; } set { _artist = value; } }
    public string Title { get { return _title; } set { _title = value; } }
    public string Album { get { return _album; } set { _album = value; } }
    public string Length { get { return _length; } set { _length = value; } }

    public ULib() {}

    public ULib(string path, string artist, string title, string album, string length) {
       Path = path;
       Artist = artist;
       Title = title;
       Album = album;
       Length = length;
    }

}

In C# there there is a short form for a property. Instead of writing code for a private variable and a setter and getter to access it, this creates that automatically:

public string Path { get; set; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...