如何获取下一个bundle中最后一个字符串的bundle项目列表


Given a list of strings:
"A"
"B"
"C"
"D"

我希望得到一个列表列表,每个项目包含 2 个项目,但第二个项目重复:

"A"、"B">

"B"、"C">

"C"、"D">

我正在尝试的是下一个可能的更好的解决方案?

//result = List<string> {"A","B","C","D"}
List<List<string>> obList = new List<List<string>>();
List<string> tst = new List<string>(2);
foreach (var s in result)
{
tst.Add(s);
if (tst.Count == 2)
{
obList.Add(tst);
tst = new List<string> { s };
}
}

一种解决方案是使用for循环迭代结果List并使用迭代器获取当前元素的范围以及列表中的下一个元素作为新列表

//You would stop the loop at the second to last element in the result list
//That way you don't get a new list with only the last element and in this 
//code block, an index out of range exception the last element would cause 
//the exception as GetRange(i, 2) on the last element would be out of range
for(int i = 0; i < result.Count - 1; i++)
{
//Grab the range    
obList.Add(result.GetRange(i, 2).ToList());
}

相关内容

最新更新