[英]how to increase the size of array or free the memory after each iteration. Error: Index was outside the bounds of the array c#
我從27 MB的文本文件讀取數據,該文本文件包含10001行,我需要處理大數據。 我對每一行數據執行某種處理,然后將其寫回到文本文件中。 這是我正在使用的代碼
StreamReader streamReader = System.IO.File.OpenText("D:\\input.txt");
string lineContent = streamReader.ReadLine();
int count = 0;
using (StreamWriter writer = new StreamWriter("D:\\ft1.txt"))
{
do
{
if (lineContent != null)
{
string a = JsonConvert.DeserializeObject(lineContent).ToString();
string b = "[" + a + "]";
List<TweetModel> deserializedUsers = JsonConvert.DeserializeObject<List<TweetModel>>(b);
var CreatedAt = deserializedUsers.Select(user => user.created_at).ToArray();
var Text = deserializedUsers.Where(m => m.text != null).Select(user => new
{
a = Regex.Replace(user.text, @"[^\u0000-\u007F]", string.Empty)
.Replace(@"\/", "/")
.Replace("\\", @"\")
.Replace("\'", "'")
.Replace("\''", "''")
.Replace("\n", " ")
.Replace("\t", " ")
}).ToArray();
var TextWithTimeStamp = Text[0].a + " (timestamp:" + CreatedAt[0] + ")";
writer.WriteLine(TextWithTimeStamp);
}
lineContent = streamReader.ReadLine();
}
while (streamReader.Peek() != -1);
streamReader.Close();
當我在輸出文件中獲得54行時,此代碼最多可以完成54次迭代。 此后,它給出錯誤“索引在數組的邊界之外”。 在線
var TextWithTimeStamp = Text[0].a + " (timestamp:" + CreatedAt[0] + ")";
我對這個問題不太清楚,是否違反了數組的最大容量,如果可以的話,如何增加它,或者如果我可以寫出循環中遇到的單個行
writer.WriteLine(TextWithTimeStamp);
並清潔存儲設備或可以解決此問題的設備。 我嘗試使用array的列表insead,仍然問題是相同的。請幫助。
更改此行
var TextWithTimeStamp = Text[0].a + " (timestamp:" + CreatedAt[0] + ")";
至
var TextWithTimeStamp = (Text.Any() ? Text.First().a : string.Empty) +
" (timestamp:" + (CreatedAt.Any() ? CreatedAt.First() : string.Empty) + ")";
在創建Text
和CreatedAt
集合對象時,根據某些方案和條件,它們可能為空(共0個項目)。
在這些情況下, Text[0]
和CreatedAt[0]
將失敗。 因此,在使用第一個元素之前,請檢查集合中是否有任何項目。 Linq
方法Any()
用於此目的。
更新資料
如果要跳過不包含文本的行,請更改此行
var TextWithTimeStamp = Text[0].a + " (timestamp:" + CreatedAt[0] + ")";
writer.WriteLine(TextWithTimeStamp);
至
if (Text.Any())
{
var TextWithTimeStamp = Text.First().a + " (timestamp:" + CreatedAt.First() + ")";
writer.WriteLine(TextWithTimeStamp);
}
更新2
要包括來自CreatedAt
所有strings
而不是僅包括第一個strings
,可以將所有值添加到逗號分隔的字符串中。 一個一般的例子
var strings = new List<string> { "a", "b", "c" };
var allStrings = string.Join(",", strings); //"a,b,c"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.