C# .NET - Getting Distinct Values of an Array?

Asked By Craig Vedur on 30-Jan-06 09:54 AM
Hi,
I have an array of structs.... How can I filter it out so I only get the DISTINCT objects?

If you're talking about

Asked By Daniel Schaffer on 30-Jan-06 10:06 AM
...something similar to the SQL DISTINCT keyword, then no, there isn't any built-in functionality that can do that. You would have to do something like this:
object[] structs = your stuff;
ArrayList distinctStructs = new ArrayList();
foreach(object oStruct in structs)
     if(!distinctStructs.Contains(oStruct)) distinctStructs.Add(oStruct);

or as a method

Asked By Daniel Schaffer on 30-Jan-06 10:30 AM
static void ClearDupes(ref YourStruct[] structs)
{
ArrayList distinct = new ArrayList();
foreach(YourStruct oStruct in structs)
if(!distinctStructs.Contains(oStruct) distinctStructs.Add(oStruct);
structs = new YourStruct[distinctStructs.Count];
distinctStructs.CopyTo(structs);
}
Either way, you get the idea.

Try a Hashtable

Asked By Peter Bromberg on 30-Jan-06 11:45 AM
using ToString or whatever construct as the key. The you can be sure all are unique
Hashtabke has Contains and ContainsKey to help with this.
you can always pull the unique items back out into an array, using the CopyTo method.
here i xplain with eg :
Asked By sajin babu on 01-Feb-06 10:09 AM
string [] arr ={"a","b","a","c"};
			ArrayList al1=new ArrayList(arr);
			ArrayList al2=new ArrayList();
			foreach(string str in al1)
			{
				if(!al2.Contains(str))
				{
					al2.Add(str);
				}
			}
			Console.WriteLine(al2.Count.ToString());
			Console.ReadLine();
atlast u will have in al2 all the distinct values