【发布时间】:2022-12-28 09:51:17
【问题描述】:
I have the following list:
List<int> Items = new List<int> { 0, 0, 1, 1, 0 }
I want same items in the array that are next to each other to continue to add up until the next item in the array that is not the same, with the output being the following:
0,2
1,2
0,1
This is the code I have:
public static void Test()
{
StringBuilder Data = new StringBuilder();
List<int> Items = new List<int> { 0, 0, 1, 1, 0 };
int Index = 1;
if (Items[0] != Items[1])
{
Data.AppendLine(Items[0] + " 1");
}
while (Index < Items.Count)
{
int PastValue = Items[Index - 1];
int CurrentValue = Items[Index];
int CurrentLength = 1;
while (CurrentValue == PastValue && Index + CurrentLength < Items.Count)
{
CurrentValue = Items[Index + CurrentLength];
CurrentLength += 1;
}
Data.AppendLine(CurrentValue + " " + CurrentLength);
Index = Index + CurrentLength;
}
Console.WriteLine(Data.ToString());
}
And it produces the following which is incorrect:
1,2
0,2
Is there a better way of doing this? Any help much appreciated.
【问题讨论】: