I nice quick and easy one here but very useful all the same.
The problem is simple. You have an array full of items that have been pulled from lots of locations and what you need is a clean array of distinct values that is also sorted. I thought this was going to be a bit of a pain but worked out that it is in fact quite simple and here’s an example of how it can be done.
Simple create a button and textbox on your form and then apply the following code,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | private void button1_Click(object sender, EventArgs e) { string[] myArray = new string[] { "qwe", "wer", "qwe", "w", "4gfg", "nhhg", "4gfg", "wer" }; string[] secondArray = RemoveDuplicates(myArray); foreach (string item in secondArray) { textBox1.Text += item + "\r\n"; } } public string[] RemoveDuplicates(string[] myList) { System.Collections.ArrayList newList = new System.Collections.ArrayList(); foreach (string str in myList) if (!newList.Contains(str)){ newList.Add(str); } newList.Sort(); return (string[])newList.ToArray(typeof(string)); } |
A few examples that I found used Linq and hash expressions, which is fine, but these did not work in DotNet2 whereas this example does.
Bish, bash, bosh. Gripped
Link to this post!
