我正在寻找帮助策略性地重命名列表中的字母数字字符串,同时保留其索引。
我为下面的代码中提到的missionList维护了几个并行列表,因此索引很重要。当用户删除列表中的一个条目时会出现问题,这些条目将在同名的任务类型之间留下间隙。
从{Mapping1,Mapping2,Mapping3}中删除Mapping2 离开{Mapping1,Mapping3},但我希望它是{Mapping1, Mapping2}。
在添加其他任务类型(如侵蚀和犯罪)之前,这并不困难。有一个未确定数量的任务类型,因此代码需要为此做好准备。
应该导致{Mapping1,Mapping3,Erosion2}的重命名操作 在{Mapping1,Mapping2,Erosion1}中。
我已在下方添加了为此设置的代码。
static void Main(string[] args)
{
List<string> missionList = new List<string> { "Mapping1", "Mapping3", "Erosion2",
"Mapping4", "Erosion3", "Crime1", "Mapping6", "Mapping8", "Erosion1" };
for (int i = 0; i < missionList.Count; i++)
{
// Get the mission number
int firstNumber = missionList[i].IndexOfAny("0123456789".ToCharArray());
int number = Convert.ToInt32(missionList[i].Substring(firstNumber));
// Get the mission name
string name = missionList[i].Substring(0, firstNumber);
//TODO: Rename missionList strings
// - Index of each string remains the same
// - Each "name" portion of the string stays the same
// - The "number" portion of the string is changed to reflect its position
// in relation to items with the same "name"
// ex. { "Mapping4", "Mapping3" } becomes { "Mapping1", "Mapping2" }
}
/* After remaming, missionList should be:
{ "Mapping1", "Mapping2", "Erosion1", "Mapping3", "Erosion2", "Crime1",
"Mapping4", "Mapping5", "Erosion3" } */
}
答案 0 :(得分:1)
这样的事情可以起作用
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
private static void DoIt()
{
Regex regex = new Regex("\\d*", RegexOptions.None);//we'll use this ro remove the existing numbers
List<string> thelista = new List<string>() { "aa11", "ab2", "aa4", "df4" };//lets fake a list
List<string> thelist = new List<string>() { "Mapping1", "Mapping3", "Erosion2", "Mapping4", "Erosion3", "Crime1", "Mapping6", "Mapping8", "Erosion1"};//Lets fake your list
List<string> templist = new List<string>();//our temp storage
Dictionary<string, int> counter = new Dictionary<string, int>();//our counting mechanism
for (int i = 0; i < thelist.Count; i++)//loop through the original list of string
{
templist.Add(regex.Replace(thelist[i], ""));//strip the number and add it to the temp list
if (!counter.ContainsKey(templist.Last()))
{
counter.Add(templist.Last(), 0);//add the type to the counter dictionnary and set the "counter" to 0
}
}
for (int i = 0; i < templist.Count; i++)//loop through the temp list
{
counter[templist[i]]++;//increment the counter of the proper type
templist[i] = templist[i] + counter[templist[i]];//add the counter value to the string in the list
}
thelist = templist;//tadam
}
输入
Mapping1
Mapping3
Erosion2
Mapping4
Erosion3
Crime1
Mapping6
Mapping8
Erosion1
输出
Mapping1
Mapping2
Erosion1
Mapping3
Erosion2
Crime1
Mapping4
Mapping5
Erosion3