比如 {3,5,4,4,4,3,6,6,5} 结果是:{2,3,4,6,7}
1 using System; 2 using System.Text; 3 using System.Collections.Generic; 4 5 namespace CSharpProject 6 { 7 class Program 8 { 9 static void Main(string[] args) 10 { 11 List<int> list = new List<int>() { 0, 0, 3, 5, 4, 4, 4, 3, 6, 6, 5, 8, 8 }; 12 StringBuilder sb = new StringBuilder(); 13 GetCloseEqualityEvenNumIndexFromList(list, ref sb); 14 Console.WriteLine(sb.ToString()); 15 16 Console.ReadKey(); 17 } 18 19 //计算List<int>中相等且连续的偶数的索引 比如 {3,5,4,4,4,3,6,6,5} 结果是:{2,3,4,6,7} 20 static void GetCloseEqualityEvenNumIndexFromList(List<int> list, ref StringBuilder sb) 21 { 22 if (null == sb) 23 sb = new StringBuilder(); 24 25 if (null != list) 26 { 27 int i = 0, iMax = 0, index = 0, counter = 0; 28 int currVal = 0, nextVal = 0; 29 sb.Append("{"); 30 for (i = 0, iMax = list.Count; i < iMax; i += (counter + 1)) 31 { 32 currVal = list[i]; 33 counter = 0; 34 for (index = i + 1; index < iMax; ++index) 35 { 36 nextVal = list[index]; 37 if (currVal == nextVal && currVal % 2 == 0 && nextVal % 2 == 0) 38 { 39 ++counter; 40 if (index - i <= 1) 41 sb.Append(i.ToString() + ","); 42 sb.Append((i + counter).ToString() + ","); 43 } 44 else 45 { 46 break; 47 } 48 } 49 } 50 sb.Remove(sb.Length - 1, 1); 51 sb.Append("}"); 52 } 53 } 54 } 55 }
结果: