具有分隔值的多个值的 C# app.config

标签 c# linq lambda app-config

我有我的 app.config文件 ArrayOfString入口。每个条目都包含一个分号分隔的字符串。如果可能的话,我希望能够使用 lambda 来解析 List<> 中的值。基于输入标准。但我想要它根据该标准找到的第一个条目。或者有没有更好的方法使用 app.config文件?

例如..

如果我想找到包含 [source],[filetype] 的第一个条目并返回文件路径。

示例 app.config条目。

SOURCE;FLAC;112;2;\\sourcepath\music\

DEST;FLAC;112;2;\\destpath\music\

最佳答案

与其依赖于让您的值落在字符串拆分操作的正确索引处,不如创建您自己的 ConfigurationSection 定义。

参见 How To on MSDNMSDN ConfigurationProperty example .

这里有一些代码可以帮助您入门:

class CustomConfig : ConfigurationSection
{
    private readonly CustomElementCollection entries =
        new CustomElementCollection();

    [ConfigurationProperty("customEntries", IsDefaultCollection = true)]
    [ConfigurationCollection(typeof(CustomElementCollection), AddItemName = "add")]
    public CustomElementCollection CustomEntries { get { return entries; } }
}

class CustomElementCollection : ConfigurationElementCollection
{
    public CustomElement this[int index]
    {
        get { return (CustomElement) BaseGet(index); }
        set
        {
            if (BaseGet(index) != null)
            {
                BaseRemoveAt(index);
            }
            BaseAdd(index, value);
        }
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new CustomElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((CustomElement)element).Name;
    }
}

class CustomElement : ConfigurationElement
{
    [ConfigurationProperty("name", IsRequired = true)]
    public string Name
    {
        get { return this["name"] as string; }
        set { this["name"] = value; }
    }

    [ConfigurationProperty("direction", IsRequired = true)]
    public string Direction
    {
        get { return this["direction"] as string; }
        set { this["direction"] = value; }
    }

    [ConfigurationProperty("filePath", IsRequired = true)]
    public string FilePath
    {
        get { return this["filePath"] as string; }
        set { this["filePath"] = value; }
    }
}

一旦指定了自定义配置,您就可以使用自定义 ConfigurationElement 中指定的任何属性通过 lambda 来Select

关于具有分隔值的多个值的 C# app.config,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10691063/

相关文章:

c# - 如何以管理员权限运行任何exe?

c# - 如何使用 EF 4.1 Code First 在运行时配置数据库连接

c# - 字符之间的正则表达式

c# - EF6 在 linq 查询中使用自定义属性

c# - 使用 "NOT IN"子句实现动态 LINQ 查询

c# - 不能在 Linqpad 中使用 "Include"

c# - 在 linq 中使用 equals 关键字

c++ - 为什么 lambda 转换为值为 true 的 bool?

c++ - 无法在 C++ 模板的初始化列表中使用 lambda

c++ - 为 lambda 分配名称会影响性能吗?