hi...now i am doing sorted list.
My problem is like this:
I got a store many groups of number in text files
eg:

112 133 121 122
133 144 155 133 122
111 111 112 124 234
122 333 221 223 345

* one line mean one transaction

I did the load file and convert the string to string array.

Now I want to do the sorted list in window form..but my sorted list got a bit problem..
So hope someone can help me..
thanks ya.....

Recommended Answers

All 13 Replies

What "a bit problem" do you have with your list?

do u want to sort them as string or as integers??

do u want to sort them as string or as integers??

sort in string array.
This is the code for sorted list I do

SortedList sortList = new SortedList();

                    foreach (string a in strArray)
                    {
                        if (!(sortList.ContainsKey(a)))
                        {
                            sortList.Add(a, 1);

                        }
                        else
                        {
                            int cnt = (int)sortList[a];
                            sortList[a] = cnt + 1;
                        }
                    }

                    IDictionaryEnumerator enumerator = sortList.GetEnumerator();

                    while (enumerator.MoveNext())
                    {
                        MessageBox.Show(enumerator.Value.ToString(), enumerator.Key.ToString());
                    }

The output is in message box. when I execute, I realize that have one value appear two times...
So, how to solve it..?

I can no longer watch the misery you still seem to have with your MessageBox.
So here is some reworked code from adatapost(you could have read that post), hope you learn from it.

IDictionaryEnumerator enu = sortList.GetEnumerator();
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            string line;
            while (enu.MoveNext())
            {
                line = enu.Value.ToString() + enu.Key.ToString(); // + means concatenation
                sb.AppendLine(line);
            }
            // messagebox OUT of while loop!
            MessageBox.Show(sb.ToString());

> I realize that have one value appear two times...

SortedList can't permit duplicate keys. Please verify key values, may be whitespace char(s) on left or right of string. Post/attach datafile and code that read and parse that datafile.

> I realize that have one value appear two times...

SortedList can't permit duplicate keys. Please verify key values, may be whitespace char(s) on left or right of string. Post/attach datafile and code that read and parse that datafile.

I got upload mt data file. Each line represent one transaction. Therefore, the data got 4 transaction only.

string[] strArray = (str).Split(' ');
                    SortedList sortList = new SortedList();

                    foreach (string a in strArray)
                    {
                        if (!(sortList.ContainsKey(a)))
                        {
                            sortList.Add(a, 1);

                        }
                        else
                        {
                            int cnt = (int)sortList[a];
                            sortList[a] = cnt + 1;
                        }
                    }

                    IDictionaryEnumerator enumerator = sortList.GetEnumerator();

                    while (enumerator.MoveNext())
                    {
                        MessageBox.Show(enumerator.Value.ToString(), enumerator.Key.ToString());
                    }

This is the code I do...
Got any need to change.

> I realize that have one value appear two times...

SortedList can't permit duplicate keys. Please verify key values, may be whitespace char(s) on left or right of string. Post/attach datafile and code that read and parse that datafile.

I got upload mt data file. Each line represent one transaction. Therefore, the data got 4 transaction only.

string[] strArray = (str).Split(' ');
                    SortedList sortList = new SortedList();

                    foreach (string a in strArray)
                    {
                        if (!(sortList.ContainsKey(a)))
                        {
                            sortList.Add(a, 1);

                        }
                        else
                        {
                            int cnt = (int)sortList[a];
                            sortList[a] = cnt + 1;
                        }
                    }

                    IDictionaryEnumerator enumerator = sortList.GetEnumerator();

                    while (enumerator.MoveNext())
                    {
                        MessageBox.Show(enumerator.Value.ToString(), enumerator.Key.ToString());
                    }

This is the code I do...
Got any need to change to solve this problem....?

Try this,

string str = System.IO.File.ReadAllText(@"C:\path\Data.txt");

            string[] ar = str.Split(new string[] { " ", "\n","\r","\t" }, StringSplitOptions.RemoveEmptyEntries);
            SortedList<string, int> sr = new SortedList<string, int>();

            foreach (var t in ar)
            {
                if (sr.ContainsKey(t))
                    sr[t]++;
                else
                    sr.Add(t, 1);
            }

            
            foreach (var m in sr)
            {
                MessageBox.Show(m.Key + " " + m.Value);
            }

Try this,

string str = System.IO.File.ReadAllText(@"C:\path\Data.txt");

            string[] ar = str.Split(new string[] { " ", "\n","\r","\t" }, StringSplitOptions.RemoveEmptyEntries);
            SortedList<string, int> sr = new SortedList<string, int>();

            foreach (var t in ar)
            {
                if (sr.ContainsKey(t))
                    sr[t]++;
                else
                    sr.Add(t, 1);
            }

            
            foreach (var m in sr)
            {
                MessageBox.Show(m.Key + " " + m.Value);
            }

thanks ya....i will try it ...

erm...my sortedlist still have the problem..now i have been try to count the appearance for the combination. But, my sorted list cannot add up itself. it will loop and give the wrong value out.

this is my data:
1 2 3 4
1 3 4

This is my coding:

private void Browse2_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog fileOpen = new OpenFileDialog())
            {
                try
                {
                    fileOpen.Filter = "All files(*.*)|*.*";
                    fileOpen.InitialDirectory = ".\\";
                    fileOpen.Title = "Open";

                    if (fileOpen.ShowDialog() == DialogResult.OK)
                    {
                        StreamReader sr2 = new StreamReader(fileOpen.FileName, Encoding.Default);
                        str2 = sr2.ReadToEnd();// read to all the contents of  data2
                        sr2.Close();

                        ContentBox2.Text = str2;
                        file2Path.Text = fileOpen.FileName;
                    }
                }

                catch (Exception o)
                {
                    string Message = o.Message + "\n\nCannot open " + fileOpen.FileName;
                    MessageBox.Show(Message, "Open error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (File.Exists(fileOpen.FileName))
                {
                    StreamReader file2 = null;
                    try
                    {
                        file2 = new StreamReader(fileOpen.FileName);

                        while ((line2 = file2.ReadLine()) != null)
                        {

                            SplitItemList1 = "";
                            //sb2.AppendLine(line2);
                            //txtCaseInputs.Text = sb2.ToString().Trim();
                            line2 = line2.Replace("\r\n"," ");
                            String[] Split2 = (line2).Split(' ');//split 

                            foreach (string byline in Split2)
                            {
                                SplitItemList1 += "\r\n" + byline;
                            }
                            // try 14/3                      
                            // MessageBox.Show(sb2.ToString().Trim());
                            sb3.AppendLine(SplitItemList1);
                            // MessageBox.Show(sb3.ToString().Trim());
                            txtCaseInputs.Text = SplitItemList1.ToString().Trim();

                            GenCombItems2();

                        }

                    }
                    catch (Exception o)
                    {
                        string Message = o.Message + "\n\nCannot open " + fileOpen.FileName;
                        MessageBox.Show(Message, "Open error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
            }

        }

        private void GenCombItems2()
        {
            int k = 2;
            int n = txtCaseInputs.Lines.Length;
          
                // txtNumCombinations.Text = Combination.Choose(n, k).ToString();

                Combination c = new Combination(n, k);

                string[] result = new string[k];

                while (c != null)
                {
                    result = c.ApplyTo(txtCaseInputs.Lines);

                    StringBuilder sb = new StringBuilder();

                    for (int i = 0; i < result.Length; ++i)
                    {
                        sb.AppendFormat("{0}{1}", result[i], " ");
                    }

                    lbCombinations2.Items.Add(sb.ToString().Trim());

                    c = c.Successor();
                }
                //txtCaseInputs.Clear();  
           
            DisplayResult2();
            // display result       
        }

        String ShowResult2 = "\n";
        SortedList list1 = new SortedList();

        private void DisplayResult2()
        {
            foreach (string sort in lbCombinations2.Items)
            {
                if (!(list1.ContainsKey(sort)))
                {
                    list1.Add(sort, 1);
                }
                else
                {
                    int Count = (int)list1[sort];
                    list1[sort] = Count + 1;
                }
            }

            IDictionaryEnumerator enumerator = list1.GetEnumerator();

            while (enumerator.MoveNext())
            {
                //ShowResult2 +=  enumerator.Key.ToString() + ":" + enumerator.Value.ToString() + "\n";
                ListItemCom2.AppendText( enumerator.Key.ToString() + ":" + enumerator.Value.ToString() + "\n");
            }
           
            SaveToTextFile2();
        }

the output i got is like this:
1 2:1
1 3:1
1 4:1
2 3:1
2 4:1
3 4:1
1 2:2
1 3:3
1 4:3
2 3:2
2 4:2
3 4:3
This is wrong output.
But, what i want is like this:
1 2:1
1 3:2
1 4:2
2 3:1
2 4:1
3 4:2
Someone can help me to fix this problem..?? Thanks ya..

Check this out:

SortedList<int, int> sList = new SortedList<int, int>();
            int[] arrayKey = { 12, 13, 14, 23, 24, 34, 12, 13, 14, 23, 24, 34 };
            int[] arrayValue = { 1, 1, 1, 1, 1, 1, 2, 3, 3, 2, 2, 3 };

            for (int i = 0; i < arrayKey.Length; i++)
            {
                if (sList.ContainsKey(arrayKey[i]))
                    sList[arrayKey[i]] = arrayValue[i];
                else
                    sList.Add(arrayKey[i], arrayValue[i]);
            }

            sList.OrderBy(a => a.Key).ToList();

I did an example code to populate the sorted list, and the correct way how to do it.
Hope it helps,
Mitja

but, My program is need to count value straight away..cannot set the value....this part is difficult.I had been try many times but still cannot do it...

private void button1_Click(object sender, EventArgs e) {
    SortedList<String, int> items = new SortedList<string,int>();
    String fileName = SelectFile();

    if (fileName != null) {
        using (StreamReader sr = new StreamReader(fileName)) {
            while (sr.EndOfStream == false) {
                String line = sr.ReadLine();
                String[] parts = line.Split();
                Combination<String> c = new Combination<string>(parts, 2);
                foreach (String[] entry in c) {
                    StringBuilder sb = new StringBuilder();
                    foreach (String str in entry) {
                        sb.Append(str);
                        sb.Append(" ");
                    }
                    String result = sb.ToString().Trim();
                    if (items.ContainsKey(result)) {
                        items[result]++;
                    } else {
                        items.Add(result, 1);
                    }
                }
            }
        }
    }

    foreach (String key in items.Keys) {
        listBox1.Items.Add(String.Format("{0} - {1}", key, items[key]));
    }
}

private string SelectFile() {
    // you can add whatever filters, etc. you want, I just needed something quick and easy
    String result = null;
    OpenFileDialog ofd = new OpenFileDialog();
    ofd.Filter = "All files(*.*)|*.*";

    if (ofd.ShowDialog() == DialogResult.OK) {
        result = ofd.FileName;
    }

    return result;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.