开发者

how to query the settingspropertyvaluecollection

I have a settingspropertyvaluecollection.I dont want to loop through all the properties using a for each 开发者_如何学编程loop.Instead i want to query the collection.How do i do that?is there a way to use LINQ and do it?

Thanks


SettingsPropertyValueCollection doesn't implement IEnumerable<T> but it does implement IEnumerable. If you want to query it using LINQ you have a couple of options.

You could create a Where() extension method that takes IEnumerable and a query and performs the query for you:

public static class IEnumerableExtensions
{
    public static IEnumerable<T> Where<T>(this IEnumerable input, Func<T,bool> query)
    {
        return input.Cast<T>().Where(item => query(item));
    }
}

assuming:

var settings = new SettingsPropertyValueCollection
    {
        new SettingsPropertyValue(new SettingsProperty("Email")
            {
                DefaultValue = "a@a.com",
                PropertyType = typeof(string)
            }),
        new SettingsPropertyValue(new SettingsProperty("City")
            {
                DefaultValue = "Austin",
                PropertyType = typeof(string)
            }),
        new SettingsPropertyValue(new SettingsProperty("State")
            {
                DefaultValue = "TX",
                PropertyType = typeof(string)
            })
    };

usage would be:

var matches = settings.Where<SettingsPropertyValue>(x => x.Name == "City")

alternatively you could use the LINQ Cast<T> operator to query the settings:

var matches = settings.Cast<SettingsPropertyValue>()
                      .Where(x => x.Name == "City");

if you expect only one possible match then use FirstOrDefault() instead of Where()

var match = settings.Cast<SettingsPropertyValue>()
                    .FirstOrDefault(x => x.Name == "City");


It's been a while since the question was answered and many things have changed since then. You could cast the SettingsPropertyValueCollection to a list (or other container) and query it right away. So, this would be my solution nowadays:

SettingsPropertyValueCollection settings = Properties.Settings.Default.PropertyValues
settings.Cast<SettingsPropertyValue>().ToList().Where(p => p.Name == "myProperty");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜