Hello,
I have List collection that is populated in specific order (the requirement is that, this order can not be changed). This list contains entity type objects.
After initial population of the list, I need to insert few more object, that are coming from another data source. These objects need to be inserted at specific position, so that sorting is correct.
For example if initial list has following elements
- AAA
- AAB
- AAC
- ACC
- ADA
After initial population I want to insert "ABB" element, it need to be inserted between 3 and 4.
At moment I have following method of finding correct position for new elements.
private static int FindPositionForArticle(string word)
{
string key = word.ToLower();
for (int i = word.Length; i >= 0; i--)
{
if(i < word.Length)
key = key.Remove(i, 1);
int pos = 0;
int insertPos = 0;
foreach(ArticleEntity article in list)
{
if(article.Text.ToLower().StartsWith(key))
insertPos = pos;
else if (!article.Text.ToLower().StartsWith(key) && insertPos > 0)
return insertPos++;
pos++;
}
}
return 0;
}
The purpose idea behind this method:
Take "word" that need to be inserted and try to find position of element with same name as "word"
If nothing has been found, remove last character from "word" and search again.
Repeat removal of last characters until best position has been found.
Unfortunately my methods has bugs(implemented incorrectly). Currently my methods suggests that best position would be 0, which is totally incorrect.
If You want to play with my example code You may download it at:
http://dl.getdropbox.com/u/204110/FindPosition.cs.txt
Thank You in advance.