XAMLab(ザムラボ)
ザムラボ - XAML研究室、WPF、Silverlight関連など。

目次

Blog 利用状況
  • 投稿数 - 202
  • 記事 - 1
  • コメント - 1191
  • トラックバック - 43
ニュース

書庫

日記カテゴリ

ギャラリ

なか-chan関連サイト

他の方へのリンク

 

ソートが旬ということで...
話題の方向性とは、ちょっと違いますが...

 

このリストをソートしようとすると...

 

こうなります。単にListBoxのSortをtrueに
するだけでは、1の次に10が来てしまったりして
数字順に並びませんね。そこで、
StrCmpLogicalWというAPIを使い並び替えを
行います。エクスプローラのファイル名順と同じ
並び替えが実現できます。
ソースの例は下記を参照してください。(Visual C# 2008)

private void button1_Click(object sender, EventArgs e)
{
    listBox1.Sorted = true;
}

private void button2_Click(object sender, EventArgs e)
{
    List<string> items =
        new List<string>(listBox1.Items.OfType<string>());
    items.Sort(new NumericComparer());
    listBox2.Items.Clear();
    listBox2.Items.AddRange(items.ToArray());
}

public class NumericComparer
    : System.Collections.Generic.IComparer<string>
{
    [System.Runtime.InteropServices.DllImport(
        "shlwapi.dll",
        CharSet = System.Runtime.InteropServices.CharSet.Unicode,
        ExactSpelling = true)]
    public static extern int StrCmpLogicalW(string x, string y);

    public int Compare(string x, string y)
    {
        return StrCmpLogicalW(x, y);
    }
}

投稿日時 : 2008年7月8日 3:22
コメント
  • # re: 数字順のソート
    Streetw☆
    Posted @ 2008/07/08 10:15
    へぇ~~。¢(. .。)
  • # re: 数字順のソート
    επιστημη
    Posted @ 2008/07/08 11:31
    return Int32.Parse(x).CompareTo(Int32.Parse(y)) よりおいしいの?
  • # re: 数字順のソート
    なか-chan
    Posted @ 2008/07/08 12:43
    数字だけではなく、いろんな文字がくっついたりしているときにはおいしいかも!?
  • # 【20080920東京勉強会#24】準備エントリ
    はつね
    Posted @ 2008/08/12 16:07
    【20080920東京勉強会#24】準備エントリ
タイトル
名前
Url
コメント