Pages

Thursday 29 January 2009

Sorting and De-duping arrays

I seem to be obsessed with sorting based on the number of posts I've made on the topic.
Sorting a simple string[] is easy using:

string[] recordIds = { "q", "z", "a", "b", "q" };
 
Array.Sort(recordIds);

To stop a third party component from failing we had to ensure that our string[] array contained only unique strings. Sorting and de-duping using LINQ could be done in a single line:

string[] recordIds = { "q", "z", "a", "b", "q" };
 
var sortedUniqueIds = (from id in recordIds orderby id select id).Distinct();
 
int i=0;
foreach (string id in sortedUniqueIds)
{
   recordIds[i++] = id;
}

Microsoft have an excellent LINQ samples page: 101 LINQ Samples

No comments: