Teddy
Teddy

Reputation: 55

How to write list of integer to file for load in other time?

I'm novice at c#, so it may little bit silly.

I want to write list of integer or array of integer to file.

If I use C, I may write down as following.

For Saving

int a[1024] = {0,};
fwrite(a,sizeof(int),1024,fp);

For Loading

int *a = null;
fseek(fp, 0, SEEK_END);

int ArraySize = ftell(fp)/sizeof(int);

a = (int*)malloc(sizeof(int)*ArraySize);
fread(a,sizeof(int),1024,fp);

Is there any good way to saving and loading?

Following is my c# code.

Saving

List<List<int>> a = new List<List<int>>();
...
...
StreamWriter wt = new StreamWriter(path);
foreach(List<int> i in a)
{
    wt.WriteLine(string.Join(",",i));
}

Loading

List<List<int>> a = new List<List<int>>();
...
...
StreamReader rd = new StreamReader(path);
string s = "";
while((s=rd.ReadLine())!=null)
{
    a.add(s.split(',').select(int.Parse).toList());
}

If you guys have any idea, help me.

Upvotes: 0

Views: 2568

Answers (2)

TheGeneral
TheGeneral

Reputation: 81573

You can use the File Methods WriteAllLines and ReadLines, and some linq

// writing
var a = new List<List<int>>();
File.WriteAllLines("filename", a.Select(x => string.Join(",", x)));

// reading , you will need to read each line, split, then parse
var result = File.ReadLines("filename")
                 .Select(x => x.Split(',').Select(int.Parse).ToList())
                 .ToList();

if you want to do this without parsing and splitting (in a more efficient manner), you can store the list in binary file

var list = new List<List<int>>();

using (var writer = new BinaryWriter(new FileStream("FileName", FileMode.Create)))
{
   foreach (var inner in list)
   {
      writer.Write(inner.Count);
      foreach (var item in inner)
         writer.Write(item);
   }
}

var results = new List<List<int>>();

using (var reader = new BinaryReader(new FileStream("FileName", FileMode.Open)))
{
   while(reader.BaseStream.Position < reader.BaseStream.Length)
   {
      var size = reader.ReadInt32();

      var inner = new List<int>(size);
      results.Add(inner);
      for (int i = 0; i < size; i++)
         inner.Add(reader.ReadInt32());
   }
}

Upvotes: 1

Anu Viswan
Anu Viswan

Reputation: 18163

You could make use of File.WriteAllLines and File.ReadAllLines. For example,

Write to File

File.WriteAllLines(filePath,list.Select(x=>x.ToString()));

Read From File

var readList = File.ReadAllLines(filePath).Select(x=>Convert.ToInt32(x)).ToList();

The Enumerable.Select projects each element of the sequence (in this case, all lines read from the text file) to Integers using the `Convert.ToInt32' method.

Upvotes: 5

Related Questions