我正在尝试根据必须按顺序排列的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();
}
converlist =
盎司,克,28.0
盎司,假,28.0 - 假一个我添加的例子
克,盎司,3.0 - 我在实例中添加假一个
磅,盎司,16.0
磅,公斤,0.454
品脱,升,0.568
英寸,厘米,2.5
英里,英寸,63360.0
如果用户键入5,盎司,克,当通过“matchedOne”时,它会找到; “一次,克,28.0”和“盎司,假,28.0”。不是那些,“磅,盎司,16.0”和“克,盎司,3.0”,就像现在一样。
然后在“matchTwo”中,它只能找到“一次,克,28.0”而不是“克,盎司,3.0”
- 只是补充一点:我不能在“系统”上使用任何东西。
答案 0 :(得分: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]));
答案 1 :(得分: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);