c# - 根据循环中另一个字典的值更新文本文件中的值

标签 c# algorithm

假设我有存储日志数据的文本文件

2019-03-01 20:00:18; Value1; Value2
2019-03-01 20:00:23; Value1; Value2
2019-03-01 20:00:28; Value1; Value2

我在字典中有值

ID = Value1
StartDateTime = 2019-03-01 20:00:18
OffDateTime = 2019-03-01 20:00:27
Value = 9

我想更新文本文件中持续时间介于 StartDateTime 和 OffDateTime 之间的所有记录中的 Value1。

在这种情况下,它将更新第一行和第二行。

我现在正在用这个

if (textFileCurrentLineDateTime >= StartDateTime && textFileNextLineDateTime < OffDateTime)
{
   //this line need to update value
}

如果 StartDateTime 和 OffDateTime 的持续时间不超过 1 条记录,则可以正常工作。

最佳答案

   internal class Program
{
    private static Line CreateLineFromString(string line)
    {
        string[] array = line.Split(';');

        return new Line
        {
            DateTime = Convert.ToDateTime(array[0],CultureInfo.InvariantCulture),
            Value1 = array[1],
            Value2 = array[2]
        };
    }

    private static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");

        IEnumerable<Line> lines = ReadLines().ToList();

        var startDate = new DateTime(2019, 1, 1);
        var endDate = new DateTime(2019, 6, 30);

        foreach (Line line in lines.Where(line => line.DateTime >= startDate && line.DateTime <= endDate)) line.Value1 = "New Value";

        SaveLines(lines);
    }


    private static IEnumerable<Line> ReadLines()
    {
        using (var reader = new StreamReader("d:\\TextFile1.txt"))
        {
            string stringLine;
            while ((stringLine = reader.ReadLine()) != null)
                if (stringLine != string.Empty)
                    yield return CreateLineFromString(stringLine);

        }
    }

    private static void SaveLines(IEnumerable<Line> lines)
    {
        using (var writer = new StreamWriter("d:\\TextFile1.txt",false))
        {
            foreach (Line line in lines) writer.WriteLine(line.ToString());
        }
    }
}


public class Line
{
    public DateTime DateTime { get; set; }
    public string Value1 { get; set; }

    public string Value2 { get; set; }

    public override string ToString()
    {
        return $"{DateTime.ToString(CultureInfo.InvariantCulture)};{Value1};{Value2}";
    }
}

关于c# - 根据循环中另一个字典的值更新文本文件中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56377662/

相关文章:

c# - 如何修改通过 C# 代理传递的 RTSP 数据

c# - 从 Linq Group By 输出 2 个字段

python - "Connectedness"在随机生成的图中

python - python中用于图像清晰度或模糊度估计的任何现有代码/库?

algorithm - 找出给定的负递归关系的时间复杂度

javascript - 寻找号码选择的可能性

c# - 删除对扩展的引用

c# - 如何在反射中迭代列表

arrays - 如何查找至少出现 K 次的数组项

c# - 如何正确使用写入固定大小缓冲区(此处为 `Read()` )的 `TcpClient` 方法?