Reputation: 13
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
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
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
Reputation: 1446
Think about the following points:
SortedList<int, String>
) with a correct IComparer<int>
(try Comparer<int>.Default
)list.ContainsKey(n) == true && list.ContainsKey(n + 1) == false
- then the next ID is n + 1
I wanted to post this as a comment but it doesn't work with the formatting :-/.
Upvotes: 1
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
no empty string, no nulls, etc.
Upvotes: 0