开发者

C# basic Dictionary Ordering Just need to clear an error

I adjusted this more and came up with the following code and I think my only problem is how I instruct it to read from textbox1 and output into textbox2 with the sorting instructions. I've been fighting this for days off and on if someone could help me out, thanks!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        System.Collections.Generic.Dictionary<string, int> myDict = new Dictionary<string,开发者_运维知识库 int>();
        myDict.Add("one", 1);
        myDict.Add("four", 4);
        myDict.Add("two", 2);
        myDict.Add("three", 3);

        var sortedDict = (from entry in myDict orderby entry.Value ascending select entry);

        string[] items = textBox1.Text.Split(Environment.NewLine.ToCharArray());
        Array.Sort(items, new ??? ());  
        textBox2.Text = String.Join(Environment.NewLine, items);




    }

}
}


It doesn't matter what order you put things in your dictionary as they will be reordered by the framework. Your Comparer should have a Compare method that looks a little like this

public int Compare(string x, string y)
{
    return _dict[x].Compare(_dict[y]);
}

[Edit] Just saw the last (scroll-down) bit of your code. This should now look like

string[] items = textBox1.Text.Split(Environment.NewLine.ToCharArray());
Array.Sort(items, new Comparer());
textBox2.Text = String.Join(Environment.NewLine, items);


try this...

    private void button1_Click(object sender, EventArgs e)
    {
        textBox2.Lines = textBox1.Lines.OrderBy(x => x).ToArray();
    }

or with custom sorting

    private void button1_Click(object sender, EventArgs e)
    {
        textBox2.Lines = textBox1.Lines.OrderBy(x => x,new Comparer()).ToArray();
    }
    public class Comparer : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            //logic here
            return 0;
        }
    }


When you implement the IComparer interface, you have to add a definition for the Compare method, and that is what the error message you have seen said.

See this example in MSDN.


It seems like the whole problem could be worked around by simply using the SortedDictionary class instead of a normal dictionary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜