Geowigo.Models.CartridgeTag.GetLastSavegameNameInteger C# (CSharp) Method

GetLastSavegameNameInteger() public method

Gets the last integer suffix that matches a pattern of names for savegames currently added to the tag.
public GetLastSavegameNameInteger ( string name, string suffixFormat ) : int
name string Name of the savegame root
suffixFormat string Format of the integer suffix
return int
        public int GetLastSavegameNameInteger(string name, string suffixFormat)
        {
            // Bakes the regex pattern
            string regexPattern = Regex.Escape(name + String.Format(suffixFormat, @"(\d+)"));
            regexPattern = regexPattern.Replace(@"\(\\d\+\)", @"(\d+)");
            
            int dbl = 0;
            Regex r = new Regex(regexPattern);
            foreach (string n in Savegames.Where(c => c.Name.StartsWith(name)).Select(c => c.Name))
            {
                foreach (Match match in r.Matches(n))
                {
                    int i = -1;
                    if (int.TryParse(match.Groups[1].Value, out i) && i > dbl)
                    {
                        dbl = i;
                    }
                }
            }

            return dbl;
        }

Usage Example

        private CartridgeSavegame CreateSavegame(CartridgeTag tag, string nameRoot, string suffixFormat, bool isQuickSave, bool isAutoSave, Dictionary<CartridgeTag, CartridgeSavegame> dict)
        {
            if (!isQuickSave && !isAutoSave)
            {
                throw new InvalidOperationException("Savegame must be either quick save or auto save");
            }
            
            // Makes a savegame.
            string intPattern = " {0}";
            int saveId = tag.GetLastSavegameNameInteger(nameRoot, intPattern) + 1;
            CartridgeSavegame cs = new CartridgeSavegame(tag, nameRoot + String.Format(intPattern, saveId))
            {
                IsQuicksave = isQuickSave,
                IsAutosave = isAutoSave
            };

            // Sets it as the current save for the tag.
            dict[tag] = cs;

            // Returns
            return cs;
        }