如何可以复制文件在C#中字典 [英] how can copy file to dictionary in c#

查看:114
本文介绍了如何可以复制文件在C#中字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何可以复制文件在C#字典

how can copy file to dictionary in c#

推荐答案

好了,你有没有指定的文件格式。如果它的核心价值,那么你可以这样做:

Well, you haven't specified the file format. If it's "key value", then you could do something like:

string[] lines = File.ReadAllLines("file.txt");
var dictionary = lines.Select(line => line.Split(' '))
                      .ToDictionary(bits => bits[0],
                                    bits => bits[1]);



其实我不喜欢在一个时间阅读完所有的线,你要知道 - 它是罚款,如果文件虽小,但如果它的大不是很好。这是相当简单写一个方法来一次读取一行:

I don't actually like reading all the lines in at a time, mind you - it's fine if the file is small, but not nice if it's large. It's reasonably straightforward to write a method to read one line at a time:

public static IEnumerable<string> EnumerableLines(string file)
{
    using (TextReader reader = File.OpenText(file))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            yield return line;
        }
    }
}

您可以调整该文本。编码等

You can adjust this for text encodings etc.

现在查询变为:

var dictionary = EnumerableLines("file.txt")
                      .Select(line => line.Split(' '))
                      .ToDictionary(bits => bits[0],
                                    bits => bits[1]);

这篇关于如何可以复制文件在C#中字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆