0

我正在尝试根据必须按顺序排列的 2 个关键字过滤掉一个数组,到目前为止,我得到了这个:

string[] matchedOne = Array.FindAll(converList, s => s.Contains(split[1]));

string[] matchedTwo = Array.FindAll(matchedOne, s => s.Contains(split[2]));

if (matchedTwo.Length == 0)
{
    Console.Clear();
    Console.WriteLine("Sorry, Your Conversion is invalid");
    Main();
}

转换列表 =

盎司,克,28.0
盎司,假货,28.0 - 我添加的假货
克,盎司,3.0 - 我添加的假货,例如
磅,盎司,16.0
磅,千克,0.454
品脱,升,0.568
英寸,厘米,2.5
英里,英寸,63360.0

如果用户输入 5, ounce, gram, 当通过“matchedOne”时它会找到;"once,gram,28.0" 和 "ounce,fake,28.0" 。不是现在的“磅,盎司,16.0”和“克,盎司,3.0”。

然后在 "matchedTwo" 中它只会找到 "once,gram,28.0" 而不是 "gram,ounce,3.0"

- 只是补充一点:我不能在“系统;”上使用任何东西。

4

2 回答 2

0
var regex = new Regex(
      string.Format("^.*{0}.*{1}.*$",
      Regex.Escape(split[1]), Regex.Escape(split[2])),
      RegexOptions.IgnoreCase
      | RegexOptions.Multiline
      | RegexOptions.CultureInvariant
      | RegexOptions.IgnorePatternWhitespace
      | RegexOptions.Compiled
    );

Match m = regex.Match(converlist);

基本上只匹配split[1]之前的一行split[2]

或没有正则表达式

string[] match = Array.FindAll(matchedOne, s => s.IndexOf(split[1])==-1?false: s.IndexOf(split[2], s.IndexOf(split[1])) != -1);

和工作转换...

const string converlist = "ounce,gram,28.0\r\nounce,fake,28.0\r\ngram, ounce, 3.0\r\npound,ounce,16.0\r\npound,kilogram,0.454\r\npint,litre,0.568\r\ninch, centimetre,2.5\r\nmile,inch,63360.0\r\n";
var split = "5,ounce,gram".Split(new[] { ',' });
var list = converlist.Split(new[]{"\r\n"}, StringSplitOptions.RemoveEmptyEntries).ToList();
var matches = list.FindAll(s =>  s.IndexOf(split[1])==-1?false: s.IndexOf(split[2], s.IndexOf(split[1])) != -1);
var conversionLine = matches[0];
Console.WriteLine(conversionLine);
var conversionFactor = decimal.Parse(conversionLine.Split(new[] { ',' })[2]);
var valueToConvert = decimal.Parse(split[0].Trim());
Console.WriteLine(string.Format("{0} {2}s is {1} {3}s", valueToConvert, conversionFactor * valueToConvert, split[1], split[2]));
于 2013-04-16T02:08:18.250 回答
0

上面的答案可以满足您的需要,但是,这也可以。

string[] s = { "ounce,gram", "gram,ounce", "pound,carret" };

foreach (string temp in s.Where(x => (x.IndexOf("ounce")>-1) && (x.IndexOf("ounce") < x.IndexOf("gram"))))
            Debug.WriteLine(temp);
于 2013-04-16T02:53:46.883 回答