我将如何通过排序结构的数组? [英] How would I sort through an array of structs?

查看:126
本文介绍了我将如何通过排序结构的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含歌曲数据的结构:

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

我的图书馆由本 uLib 的阵列。我将如何解决这数组说艺术家?是否有原生的排序功能,我可以在此类型的数组叫,否则我将不得不推出自己的?

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"?

推荐答案

首先,这不应该是一个结构。这是大于16个字节,所以你不会有一个结构的性能优势。此外,它不会重新present一个值,所以它是没有意义的语义,使之成为结构。只要它一类代替。

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

如果您还没有C#3你使用委托,而不是拉姆达EX pression:

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

编辑:
这里是你的数据可能看起来像为一类的例子:


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

}

在C#中有有一个短格式的属性。而不是写code的私有变量和setter和getter访问它,这将创建一个自动:

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

这篇关于我将如何通过排序结构的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆