一个是整数列表,一个是字符串列表。整数列表的长度将始终是 8 的倍数。我想将整数列表中的前 8 个整数放入字符串列表的第一个元素中,然后循环并将接下来的 8 个整数放入字符串列表的第二个元素中,然后很快。我已经尝试过,我目前在 Add 方法上有一个错误,因为字符串没有添加扩展名?此外,我不确定我使用循环的方式是否正确,任何建议都会有所帮助。
List1 是我的整数列表
List2 是我的字符串列表
string x = "";
for (int i = 0; i < List1.Count/8; i++) {
for(int i2 = 0; i2 < i2+8; i2+=8)
{
x = Convert.ToString(List1[i2]);
List2[i].Add(h);
}
}
你可以通过使用类似的东西来做到这一点
var list1 = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
var list2 = new List<string>();
for (int i = 0; i < list1.Count / 8; i++)
{
list2.Add(string.Concat(list1.Skip(i * 8).Take(8)));
}
// list2[0] = "12345678"
// list2[1] = "910111213141516"
一种稍微复杂的方法,它只迭代一次list1
(与 IEnumerable 一起工作将是这样的:
var list1 = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }.AsEnumerable();
var list2 = new List<string>();
var i = 0;
var nextValue = new StringBuilder();
foreach (var integer in list1)
{
nextValue.Append(integer);
i++;
if (i != 0 && i % 8 == 0)
{
list2.Add(nextValue.ToString());
nextValue.Clear();
}
}
// could add remaining items if count of list1 is not a multiple of 8
// if (nextValue.Length > 0)
// {
// list2.Add(nextValue.ToString());
// }
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句