HI,
我有一组字符串 例如 “测试(9)” “测试(7)” “测试(5)” “test(3)”
我想循环使用foreach循环迭代并找到最小的数字我有一个正则表达式从每个字符串中提取数字...我需要循环遍历所有项目(格式如我的例子中所示)上面找到最低的数字......?
foreach (SPListItem item in items)
{
string item = (String)item["Title"];
string itemNumberString = Regex.Match(UniqueCounteryparty, @"\d+").Value;
}
答案 0 :(得分:5)
int minValue = int.MaxValue;
foreach(string s in strings)
minValue = Math.Min(minValue, ExtractNumberMethod(s));
答案 1 :(得分:3)
我正在使用数组初始化语法初始化下面的变量“test”以进行演示,因为我假设你已经有一个已经填充了你需要的字符串的集合。
string[] tests = new string[] { "test(1)", "test(2)", "test(3)" }; int minimum = int.MaxValue; foreach(string test in tests) { int num = ExtractNumber(test); if (num < minimum) minimum = num; } //now you have minimum that hold the minimum;
“ExtractNumber”是从字符串
中提取数字的函数答案 2 :(得分:0)
您可以简单地依赖基类库方法:
用于说明两种方法的示例:
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
private static void Method2(string[] strings)
{
int[] ints = new int[strings.Length];
for (int i = 0; i < strings.Length; i++)
{
ints[i] = Extract(strings[i]);
}
Array.Sort<int>(ints);
foreach (int i in ints)
{
Console.WriteLine(i);
}
Console.WriteLine("The smallest is {0}", ints[0]);
}
private static void Method1(string[] strings)
{
List<int> result = new List<int>();
foreach (string s in strings)
{
int value = Extract(s);
result.Add(value);
}
result.Sort();
foreach (int i in result)
{
Console.WriteLine(i);
}
Console.WriteLine("The smallest is {0}", result[0]);
}
static void Main(string[] args)
{
string[] strings = new string[6];
strings[0] = "test (9)";
strings[1] = "test (4)";
strings[2] = "test (7)";
strings[3] = "test (1)";
strings[4] = "test (2)";
strings[5] = "test (8)";
Console.WriteLine("\nMethod1 :");
Method1(strings);
Console.WriteLine("\nMethod2 :");
Method2(strings);
Console.ReadLine();
}
private static int Extract(string s)
{
// simply extract the digits
return Convert.ToInt32(Regex.Match(s, @"\d+").Value);
}
}
}