既然你問:「如果我們能得到哪些產品複製和啓動索引和出現次數「,這是對特定需求的解決方案。
此輸出以下:
2 was repeated 2 times starting at index 1
3 was repeated 3 times starting at index 4
4 was repeated 4 times starting at index 8
下面的代碼:
using System;
using System.Collections.Generic;
namespace Demo
{
class DupeInfo
{
public string Text;
public int Index;
public int Count;
}
static class Program
{
static void Main()
{
var test = new[]
{
"1",
"2", "2",
"A",
"3", "3", "3",
"B",
"4", "4", "4", "4",
"C",
};
foreach (var dupeinfo in FindRepeats(test))
Console.WriteLine($"{dupeinfo.Text} was repeated {dupeinfo.Count} times starting at index {dupeinfo.Index}");
}
public static IEnumerable<DupeInfo> FindRepeats(IEnumerable<string> input)
{
int i = 0;
int j = 0;
int c = -1;
string prev = null;
foreach (var curr in input)
{
if (curr != prev)
{
if (c >= 0)
yield return new DupeInfo {Text = prev, Count = c + 2, Index = j};
c = -1;
j = i;
}
else
{
++c;
}
prev = curr;
++i;
}
if (c >= 0)
yield return new DupeInfo {Text = prev, Count = c + 2, Index = j};
}
}
}
你想要什麼樣的結果?真/假結果,重復部分的列表? –
顯示您在試圖解決此問題時編寫的代碼,以便我們可以查看出錯的位置。不要忘記告訴我們爲什麼它不起作用。並調試你的代碼。 –
@ LasseV.Karlsen,如果我們可以得到哪個項目是重複的,並開始索引和發生次數。 – Pankaj