title: Finding best position for element in list
body: <p>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. </p>
  
  <p>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.</p>
  
  <p>For example if initial list has following elements</p>
  
  <ol>
  <li>AAA</li>
  <li>AAB</li>
  <li>AAC</li>
  <li>ACC</li>
  <li>ADA</li>
  </ol>
  
  <p>After initial population I want to insert "ABB" element, it need to be inserted between 3 and 4.</p>
  
  <p>At moment I have following method of finding correct position for new elements.</p>
  
  <pre><code>    private static int FindPositionForArticle(string word)        
      {
          string key = word.ToLower();
          for (int i = word.Length; i &gt;= 0; i--)
          {
              if(i &lt; 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) &amp;&amp; insertPos &gt; 0)
                      return insertPos++;
                  pos++;
              }
          }
          return 0;
      }
  </code></pre>
  
  <p>The purpose idea behind this method:</p>
  
  <ol>
  <li><p>Take "word"  that need to be inserted and try to find position of element with same name as "word"</p></li>
  <li><p>If nothing has been found, remove last character from "word" and search again.</p></li>
  <li><p>Repeat removal of last characters until best position has been found.</p></li>
  </ol>
  
  <p>Unfortunately my methods has bugs(implemented incorrectly). Currently my methods suggests that best position would be 0, which is totally incorrect.</p>
  
  <p>If You want to play with my example code You may download it at:</p>
  
  <p><a href="http://dl.getdropbox.com/u/204110/FindPosition.cs.txt" rel="nofollow noreferrer">http://dl.getdropbox.com/u/204110/FindPosition.cs.txt</a></p>
  
  <p>Thank You in advance.</p>