Home > General > Insert Distinct Records into ArrayList

Insert Distinct Records into ArrayList

Many a times we people come across a requirement where we need to find/extract/query or push/insert/add distinct records and or items into collections like Array, ArrayList, IList. So the same happened with me recently where I wanted to maintain distinct records into the arraylist object which is shared across the layers.
To suffice this requirement I tried lot many approaches and solutions (some very traditional yet time consuming, some hi-fi but too complex to implement 🙂 ) even I searched a lot for the same but could not find any handy solution. Thats the time where I came across “BinarySearch” method under ArrayList class.
I did bit analysis and then made tiny changes into my code to leverage the benifits of BinarySearch method. So becaue of this my code looked as below:

// push the metadata of Master tables by refering the MasterFieldsDataTable
for (int listIndex = 0; listIndex < MasterFieldsDetails.Count; listIndex++)
for (int rowIndex = 0; rowIndex < MasterTablesDT.Rows.Count; rowIndex++)
if (MasterTablesDT.Rows[rowIndex][“Description”].ToString().ToUpper().Equals(MasterFieldsDetails[listIndex].Discription.ToUpper()))
// processed some data here and some manipulation…..

// Add the item to Arraylist is its count is zero
if (0 == uniqueTableNames.Count)
// Do the BinarySearch for Item
int itemfound = uniqueTableNames.BinarySearch(MasterFieldsDetails[listIndex].TableName);
// If item is not found then add it to the ArrayList
if (0 > itemfound)
// Sort the Arraylist for FoolProof BinarySearch in Next Iteration


Now in above code there is 1 catch and that is because the iteration is been broken prematurely which some how affects the indexing of arraylist items. Now because of this the BinarySearch donot work and allows to add duplicate/redundent data to be added to it. So to avoid this we need to sort the arraylist.
More details on the ArrayList class and its methods can be found here: http://msdn.microsoft.com/en-gb/library/5tzt7yz3.aspx
Well this is all about my observation and approach i decided to solve the issue. Any idea, suggestion, solution will be appreciated. Similarly more details, explaination and clarity on the said issue is also appreciated.

Categories: General Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: