具有2个时间数据的LinkedList

时间:2019-05-02 22:17:25

标签: c#

我必须给txt文件中的链接表2次数据。 但我无法填写。

StreamReader sr;
public void FileReader(string file, LinkedList<Task> Tasks)
{
    string splitter= "."; 
    int TaskIndex= 0;
    sr = new StreamReader(file);
    LinkedList<Task> data = new LinkedList<Task>();            

    while (!sr.EndOfStream)
    {
        string tempString = sr.ReadLine(); 
        if (splitter== tempString) 
        {
            TaskIndex++;                    
            Tasks.Add(data);

        }               
    }            
    sr.Close();            
}

public class Task
{        
    public TimeSpan FullTime= new TimeSpan(0, 24, 0, 0); 
    public TimeSpan TaskLength { get; set; }
    public TimeSpan Deadline{ get; set; }
    public int Penalty{ get; } = 50000;
    public Task(TimeSpan TaskLength, TimeSpan Deadline)
    {
        this.TaskLength= TaskLength;
        this.Deadline= Deadline;
    }
}

和txt:前2个数据是TaskLengths小时和分钟,后2个是截止日期小时和分钟,每一行都是一个任务

  

2,30,5,0。

     

4,0,16,0。

     

1,0,2,0。

     

6,0,14,0。

     

3,30,10,0。

     

2,0,22,0。

1 个答案:

答案 0 :(得分:1)

听起来您想要做的是从文件中读取每一行,以逗号分隔该行(并删除句点,因为每一行都是一个任务),将行中的数字解析为整数,从数字创建两个TimeSpan对象,从两个Task对象创建TimeSpan对象,然后将该Task添加到LinkedList<Task>

如果是这种情况,那么这是一个示例方法,您可以将文件名传递给该方法,该方法将从文件内容中返回LinkedList<Task>

public LinkedList<Task> GetTasksFromFile(string filePath)
{
    // This will hold our results from reading the file lines into Tasks
    var tasks = new LinkedList<Task>();

    // Loop through each line in the file 
    foreach (string line in File.ReadLines(filePath))
    {
        // Split the line on the comma and period characters so we get separate values
        string[] parts = line.Split(new[] {'.', ','}, 
            StringSplitOptions.RemoveEmptyEntries);

        // These will hold the parsed values from each line of text in our file
        int lengthHour;
        int lengthMinute;
        int deadlineHour;
        int deadlineMinute;

        // int.TryParse will try to convert a string to an int, and will return 
        // true if successful. It will also set the 'out' parameter to the result.
        // We do this on each part from our line of text 
        // (after ensuring that there are at least 4 parts)
        if (parts.Length > 3 &&
            int.TryParse(parts[0], out lengthHour) &&
            int.TryParse(parts[1], out lengthMinute) &&
            int.TryParse(parts[2], out deadlineHour) &&
            int.TryParse(parts[3], out deadlineMinute))
        {
            // If our parsing succeeded, create a new task
            // with the results and add it to our LinkedList
            TimeSpan length = new TimeSpan(lengthHour, lengthMinute, 0);
            TimeSpan deadline = new TimeSpan(deadlineHour, deadlineMinute, 0);
            Task task = new Task(length, deadline);
            tasks.AddLast(task);
        }
    }

    // Return our linked list back to the caller
    return tasks;
}