gpt4 book ai didi

c# - 计算 List 中的相似相邻项

转载 作者:太空狗 更新时间:2023-10-30 01:34:51 26 4
gpt4 key购买 nike

我试图在列表中找到相似的相邻项目并计算其数量,例如:

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);
}
}

关于c# - 计算 List<string> 中的相似相邻项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28648409/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com