只是为了我的好奇心。
var originalList = new List<string>
{
"1235 \t This is Record 1",
"7897 \t This is Record 2",
"8977 \t This is Record 3",
"continued on the next line",
"and still continued more",
"8375 \t This is Record 4"
};
var resultList = new List<string>();
resultList.Add(originalList.Aggregate((workingSentence, next)
=> {
if (next.Contains("\t"))
{
resultList.Add(workingSentence);
return next;
}
else
{
workingSentence += "|" + next;
return workingSentence;
}
}));
resultList应该包含你想要的。
请注意,这不是一个最佳解决方案。行workingSentence += "|" + next;
可能会根据您的数据模式创建大量临时对象。
最佳解决方案可能涉及到保持多个索引变量在字符串之前,并在下一个字符串包含制表符时将它们连接起来,而不是如上所示逐个连接。但是,由于边界检查和保留多个索引变量,它会比上面的更复杂:)。
更新:以下解决方案不会创建用于连接的临时字符串对象。
var resultList = new List<string>();
var tempList = new List<string>();
tempList.Add(originalList.Aggregate((cur, next)
=> {
tempList.Add(cur);
if (next.Contains("\t"))
{
resultList.Add(string.Join("|", tempList));
tempList.Clear();
}
return next;
}));
resultList.Add(string.Join("|", tempList));
以下是使用for
循环的解决方案。
var resultList = new List<string>();
var temp = new List<string>();
for(int i = 0, j = 1; j < originalList.Count; i++, j++)
{
temp.Add(originalList[i]);
if (j != originalList.Count - 1)
{
if (originalList[j].Contains("\t"))
{
resultList.Add(string.Join("|", temp));
temp.Clear();
}
}
else // when originalList[j] is the last item
{
if (originalList[j].Contains("\t"))
{
resultList.Add(string.Join("|", temp));
resultList.Add(originalList[j]);
}
else
{
temp.Add(originalList[j]);
resultList.Add(string.Join("|", temp));
}
}
}
说实话,这不是我会建议使用LINQ的,尽管我确信有办法这样做。这与它的设计不符。 – Servy 2012-03-29 23:53:42