只是爲了我的好奇心。
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