我希望从列表中检索(按连续顺序)匹配表达式的元素,但目前我没有看到(performant)解决方案。
例如:
var items = new List<string>
{
"1",
".",
"249",
"something",
"1", // 5
".", // 6
"250", // 7
"yes"
};
// I am looking for the consecutive elements that form the expression below (5-6-7).
var match = "1.250";
var elements = ...;发布于 2019-10-23 22:13:23
这里有一种简单的方法,嵌套不超过1层。
这将找到第一个匹配项。如果未找到匹配项,则在循环后,indexes的计数将为0。把你选择的方法放在里面。
List<int> indexes = new List<int>();
for (int i = 0; i < items.Count; i++)
{
string temp = items[i];
while (temp.Length < match.Length && temp == match.Substring(0, temp.Length) && i < items.Count - 1)
{
indexes.Add(i + 1); // example was given using 1-based
temp += items[++i];
}
if (temp == match)
{
indexes.Add(i + 1);
break; // at this point, indexes contains the values sought
}
indexes.Clear();
}对于包含10,000个元素的列表,要查找的元素位于末尾,运行时间约为0.0003775秒。
发布于 2019-10-23 22:18:35
这应该会给出一个答案,但是如果有多个匹配项,它会返回最后一个匹配项。
public static void GetConsecutiveMatch(List<String> items, String match, out List<int> indices)
{
indices = new List<int>();
for (int i = 0; i < items.Count(); i++)
{
var strToCompare = "";
for (int j = i ; j < items.Count(); j++)
{
strToCompare += items[j];
if (strToCompare.Length == match.Length)
{
if (strToCompare == match)
{
indices.Clear();
for (int k = i; k <= j; k++)
{
indices.Add(k + 1); // at your example indices seems to be starting at 1, so I added 1 to the actual index
}
}
break;
}
else if (strToCompare.Length > match.Length)
{
break;
}
}
}
}发布于 2019-10-23 22:26:14
public IEnumerable<int> GetMatch(List<string> items, string match)
{
string str = null;
for (int i = 0; i < items.Count; i++)
{
if (!match.StartsWith(items[i]))
continue;
for (int j = 1; j < items.Count - i + 1; j++)
{
str = items.Skip(i).Take(j).Aggregate((x, y) => x + y);
if (str.Equals(match))
return Enumerable.Range(i + 1, j).Select(x => x).ToList();
else if (match.StartsWith(str))
continue;
break;
}
}
return new int[0];
}
[Fact]
public void Test()
{
var items = new List<string> { "1", ".", "249", "something", "1", ".", "250", "yes" };
var match = "1.250";
var matchingIndexes = GetMatch(items, match);
Assert.True(matchingIndexes.Any());
Assert.Equal(5, matchingIndexes.ElementAt(0));
Assert.Equal(6, matchingIndexes.ElementAt(1));
Assert.Equal(7, matchingIndexes.ElementAt(2));
}https://stackoverflow.com/questions/58524194
复制相似问题