从字符串中过滤字符串

时间:2014-08-04 03:05:32

标签: c# arrays filter .net-3.5

我试图设计对数组的传入字符串进行检查,如果传入的字符串具有特定的起始字符,则会跳过

例如:

;item1
item2
item3
;item4

应该作为

放入数组
item2
item3

我以为我尝试使用foreach方法跳过以标识符开头的行,然后在else中添加不匹配回字符串数组的行,但它没有&似乎我能够做到这一点。

帮助!

    void Whitelist()
    {
        if (logging == 1)
        {
            FIO._Log("Performing WhiteList func", writer);
        }
        try
        {
            string[] lines = File.ReadAllLines("Whitelist.ini");
            string[] lines2;
            foreach (string line in lines)
            {
                if (line.StartsWith(";"))
                {
                    continue;
                }
                else
                {
                    // lines2.append(line) ??
                }

            }
            structs.CustomWhiteList = lines2;
        }
        catch (Exception e)
        {
            MessageBox.Show("Error reading whitelist file." + Environment.NewLine + e.Message);
            FIO._Log("Failed to read whitelist file", writer);
        }
    }

1 个答案:

答案 0 :(得分:2)

您可以读取这些行,过滤掉以分号开头的行,然后将结果数组直接设置为CustomWhiteList

请尝试以下代码:

var lines = File.ReadAllLines("Whitelist.ini");

structs.CustomWhiteList = lines.Where(x => !x.StartsWith(";")).ToArray();

这使用LINQ,因此如果您的课程尚不存在,则必须将using System.Linq添加到您的课程中。

相关问题