将List <string>替换为文件中的单词,保留顺序</string>

时间:2014-07-24 06:55:18

标签: c# string list foreach streamreader

public static List<string> items = new List<string>() { "a","b","c","d","e" };

我正在尝试更改每个加载文件并替换当前库存。

if (File.Exists("darColItems.txt") == true)
{
    char c = ',';
    StreamReader st = new StreamReader("darColItems.txt");
    temp = st.ReadToEnd().ToCharArray();
    foreach (c in temp)
    {

    }
    st.Close();
}

编辑:取一个文件,如:铁,青铜,金,钻石,铁,并取每个名称,并将其放入每个地点的列表。

File.txt:"string1","string2","string3","string4","string5"

启动计划:

列出库存(当前):

"a","b","c","d","e"

加载广告资源....

列出库存(最终):

"string1","string2","string3","string4","string5"

2 个答案:

答案 0 :(得分:2)

假设您确实要按照出现的顺序将列表中的所有项目替换为文件中的所有项目,并且分隔符为逗号。您可以使用String.Split

items = File.ReadAllText("path").Split(new [] { ',' }, StringSplitOptions.None).ToList();

如果您要删除文件中的字词,则可以使用String.Trim

items = File.ReadAllText("path")
    .Split(new char[] { ',' }, StringSplitOptions.None)
    .Select(s => s.Trim('"', ' '))  // remove quotes + spaces at the beginning and end
    .ToList();

答案 1 :(得分:0)

//keep filename in a constant/variable for easy reuse (better, put it in a config file)
const string SourceFile = "darColItems.txt";

//what character separates data elements (if the elements may contain this character you may instead want to look into a regex; for now we'll keep it simple though, & assume that's not the case
const char delimeter = ',';

//here's where we'll store our values
var values = new List<string>();

//check that our input file exists
if (File.Exists(SourceFile))
{
    //using statement ensures file is closed & disposed, even if there's an error mid-process
    using (var reader = File.OpenText(SourceFile))
    {
        string line;
        //read each line until the end of file (at which point the line read will be null)
        while ((line = reader.ReadLine()) != null)
        {
            //split the string by the delimiter (',') and feed those values into our list
            foreach (string value in line.Split(delimiter)
            {
                values.Add(value);
            }
        }
    }
}