开发者

how to insert text file to <list>

开发者 https://www.devze.com 2023-02-06 01:59 出处:网络
how to insert text file to <list> for example text file: 1. t开发者_Python百科his error 2. delete ?

how to insert text file to <list> for example text file:

1. t开发者_Python百科his error
2. delete ?
3. add new ?

how to insert to and how to retrieve message by number

for example for the number 2 i'll get delete ?

thanks in advance


Quick and dirty:

var lines = File.ReadAllLines("Questions.txt");
var questions = new Dictionary<int, string>();
foreach (var line in lines)
{
    var parts = line.Split(new[] {". "}, StringSplitOptions.RemoveEmptyEntries);
    var number = Int32.Parse(parts[0]);
    questions.Add(number, parts[1]);
}

To get question 2:

var q2 = questions[2];

Example:

class Quiz
{
    private Dictionary<int,string> _questions;

    public Quiz(string questionsFileName)
    {
        LoadQuestions(questionsFileName);
    }

    public string PoseQuestion(int number)
    {
        Console.WriteLine(_questions[number]);
    }

    private LoadQuestions(string fileName)
    {
        var lines = File.ReadAllLines(fileName);
        _questions = new Dictionary<int, string>();
        foreach (var line in lines)
        {
            var parts = line.Split(new[] {". "}, StringSplitOptions.RemoveEmptyEntries);
            var number = Int32.Parse(parts[0]);
            _questions.Add(number, parts[1]);
        } 
    }
}


I didn't compile it but if I understand you correctly you are looking for something similar to this. You should add the appropriate error handling.

Dictionary<int, string> map = new Dictionary<int, string>();    

using (FileStream fs = new FileStream(inputFile, FileMode.Open)
using (StreamReader sr = new StreamReader(fs)
{
    while (sr.Peek() >= 0) 
    {
        string[] split = string.Split(".", sr.ReadLine());

        int num = int.Parse(split[0]);
        string msg = split[1];

        map.Add(num, msg);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消