[英]how to save the linked list to text file? in C#
How to save this content in text file? 如何将这些内容保存在文本文件中? in C# 在C#中
using System;
using System.Collections.Generic;
using System.Text;
namespace LinkList
{
class Program
{
static void Main(string[] args)
{
list x = null;
list first;
Random rnd = new Random();
x = new list();
first = x;
x.data = rnd.Next(20, 500);
x.next = null;
for (int i = 0; i < 20; i++)
{
x.next = new list(); //create new node
x = x.next;
x.next = null;
//x.data = System.Convert.ToInt32(Console.ReadLine());
x.data = rnd.Next(20, 500);
}
x = first;
int count = 0;
int y;
while (x != null)
{
Console.WriteLine(x.data);
x = x.next;
}
}
}
class list
{
public int data; //4 byte
public list next; // 4 byte
}
}
One possible way would be to serialize it. 一种可能的方法是序列化它。 JSON is a pretty standard format, so you could use a JSON serializer such as Newtonsoft.JSON
: JSON是一种非常标准的格式,因此您可以使用JSON序列化程序,例如Newtonsoft.JSON
:
string json = JsonConvert.SerializeObject(first);
File.WriteAllText("list.txt", json);
Or if you don't want to use third party libraries you could use the JavaScriptSerializer
class that's built into the framework to achieve the same: 或者,如果您不想使用第三方库,则可以使用框架中内置的JavaScriptSerializer
类来实现相同目的:
string json = new JavaScriptSerializer().Serialize(first);
File.WriteAllText("list.txt", json);
If you prefer XML as serialization format you could do this instead: 如果您更喜欢XML作为序列化格式,则可以这样做:
var serializer = new XmlSerializer(typeof(list));
using (var output = File.OpenWrite("list.xml"))
{
serializer.Serialize(output, first);
}
For this to work you might need to make the list
class public
because in your example it is internal
. 为此,您可能需要使list
类public
因为在您的示例中它是internal
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.