我试图在列表中找到相似的相邻项目并计算其数量,例如:
List<string> list = new List<string> {"a", "a", "b", "d", "c", "c"};
期望的输出:
a = 2,c = 2
我所做的是使用 for 循环迭代列表中的每个元素并查看它是否具有相似的相邻元素,但可以理解的是,它给出了ArgumentOutOfRangeException()
因为我不知道如何跟踪迭代器的位置,以免它超出范围。这是我所做的:
for (int j = 0; j < list.Count; j++)
{
if (list[j] == "b")
{
if ((list[j + 1] == "b") && (list[j - 1] == "b"))
{
adjacent_found = true;
}
}
}
话虽如此,如果除了使用 for 循环迭代之外,还有另一种更简单的方法可以在 List 中查找相似的相邻元素,请告知。谢谢。
你可以这样做:
static IEnumerable<Tuple<string, int>> FindAdjacentItems(IEnumerable<string> list)
{
string previous = null;
int count = 0;
foreach (string item in list)
{
if (previous == item)
{
count++;
}
else
{
if (count > 1)
{
yield return Tuple.Create(previous, count);
}
count = 1;
}
previous = item;
}
if (count > 1)
{
yield return Tuple.Create(previous, count);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)