Scarsz
Scarsz

Reputation: 13

Get next available ID from array of names

I have 3 strings, each contained within an array.

string[] folderArray = {"1 - Name", "4 - Another name", "3 - Another name"}

I need to get the next available ID (folder number) available.

For the example, the ID required would be 2 because it would see that the "2" ID is missing from the array.

A PHP duplicate of this question can be found at Finding first available ID from an array

Upvotes: 0

Views: 802

Answers (4)

aryan_curiel
aryan_curiel

Reputation: 33

if you use the SortedList class, you will fix the problem...Look this code

SortedList<int, string> lista = new SortedList<int, string>();
lista.Add(4, "Name");
lista.Add(1, "Name");
lista.Add(3, "Name");
lista.Add(7, "Name");
int nextID = 1;
foreach (var item in lista.Keys)
{
   if (nextID != item) break;
   else nextID++;
}
Console.WriteLine(nextID);

The SortedList class recieve a TKey parameter, and a TValue parameter. She sort the elements by the TKey parameter. You only have to add the elements in the list, and she'll do the works for you...Then, search the next Id no exist in the list. The lista.Keys returns an IEnumerable with all the keys added, in decrease order...

Upvotes: 2

Med.Amine.Touil
Med.Amine.Touil

Reputation: 1235

Try this code

    string[] folderArray = { "1 - Name", "4 - Another name", "3 - Another name" };
    var listId = new List<int>();
    foreach (var item in folderArray)
    {
       var tempId = 0;
        if (int.TryParse(item.Split('-')[0].Trim(), out tempId))
           listId.Add(tempId);
    }




   listId.Sort();
   for (var i=1 ;i<listId.Count ;i++)
   {
      if(listId[i]-listId[i-1]>1)
        {
          Console.WriteLine(listId[i-1]+1);
          break;
        }
   }

Upvotes: 0

PermaFrost
PermaFrost

Reputation: 1446

Think about the following points:

  • Don't use an array of strings, use a sorted collection (e.g. SortedList<int, String>) with a correct IComparer<int> (try Comparer<int>.Default)
  • Then iterate in order and find the first gap where gap means: list.ContainsKey(n) == true && list.ContainsKey(n + 1) == false - then the next ID is n + 1
  • For performance enhancements, you could memorize the last ID you gave to a caller (or the last folder that was deleted if that is supported as well) and start searching from there for the next request for an ID

I wanted to post this as a comment but it doesn't work with the formatting :-/.

Upvotes: 1

Szabolcs D&#233;zsi
Szabolcs D&#233;zsi

Reputation: 8843

I wouldn't do it like this, but if you would like the same as in the PHP solution you linked:

var missing = Enumerable.Range(1, folderArray.Length).Except(folderArray.Select(f => int.Parse(f.Split('-').First()))).First();

Note: This has the assumption that the items in the folderArray are always in the form

  • "[number] - [some string]"

no empty string, no nulls, etc.

Upvotes: 0

Related Questions