0
我有一個settingspropertyvaluecollection.I不想循環遍歷所有的屬性使用每個loop.Instead我想查詢集合。我該怎麼做?有沒有一種方法來使用LINQ和做它?如何查詢settingspropertyvaluecollection
感謝
我有一個settingspropertyvaluecollection.I不想循環遍歷所有的屬性使用每個loop.Instead我想查詢集合。我該怎麼做?有沒有一種方法來使用LINQ和做它?如何查詢settingspropertyvaluecollection
感謝
SettingsPropertyValueCollection沒有實現IEnumerable < T>,但它確實實現IEnumerable。如果你想用LINQ查詢它,你有兩個選擇。
您可以創建一個需要IEnumerable和查詢,併爲您執行的查詢在哪裏()擴展方法:
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));
}
}
假設:
var settings = new SettingsPropertyValueCollection
{
new SettingsPropertyValue(new SettingsProperty("Email")
{
DefaultValue = "[email protected]",
PropertyType = typeof(string)
}),
new SettingsPropertyValue(new SettingsProperty("City")
{
DefaultValue = "Austin",
PropertyType = typeof(string)
}),
new SettingsPropertyValue(new SettingsProperty("State")
{
DefaultValue = "TX",
PropertyType = typeof(string)
})
};
用法是:
var matches = settings.Where<SettingsPropertyValue>(x => x.Name == "City")
或者您可以使用LINQ Cast < T>操作符來查詢se設置:
var matches = settings.Cast<SettingsPropertyValue>()
.Where(x => x.Name == "City");
,如果你希望只有一個可能的匹配,然後使用FirstOrDefault(),而不是在哪裏()
var match = settings.Cast<SettingsPropertyValue>()
.FirstOrDefault(x => x.Name == "City");