我在查找字符串列表中的下一个整数匹配时遇到问题,需要考虑其他一些方面:
示例:
用户输入为7 =>下一个匹配的字符串为abcd-000008.file
我的尝试是:
int userInput = 0;
int counter = 0;
string found = String.Empty;
bool run = true;
while (run)
{
for (int i = 0; i < strList.Count; i++)
{
if(strList[i].Contains((userInput + counter).ToString("D6")))
{
found = strList[i];
run = false;
break;
}
}
counter++;
}
这很糟糕,因为它很慢,并且可能会变成无限循环。但是我真的不知道该怎么做(快速)。
List<string> strings = new List<string>
{
"abc-000001.file",
"aaac-000002.file",
"ab-0002010.file",
"abbc-000003.file",
"abbbc-000004.file",
"abcd-000008.file"
};
int input = 7;
var converted = strings.Select(s => new { value = Int32.Parse(s.Split('-', '.')[1]), str = s })
.OrderBy(c => c.value);
string result = converted.FirstOrDefault(v => v.value >= input).str;
Console.WriteLine(result);
Regex
解析字符串中的数字,并创建一个可以使用Where
子句进行搜索的排序集合:var strings = new[] { "abc-000001.file", "x-000004.file"};
var regP = "\\d{6,}"; // simplest option in my example, maybe something more complicated will be needed
var reg = new Regex(regP);
var collection = strings
.Select(s =>
{
var num = reg.Match(s).Captures.First().Value;
return new { num = int.Parse(num), str = s};
})
.OrderBy(arg => arg.num)
.ToList();
var userInput = 2;
var res = collection
.Where(arg => arg.num >= userInput)
.FirstOrDefault()?.str; // x-000004.file
P.S。如何处理
9002010
,0000010
,0002010
?因为它们有7个字符。是[9002010,10,2010]还是[900201,1,201]?