如果我有一个ConfigurationSection类型的集合,如何在集合中搜索?
(我是C#noob和业余爱好者)
我有这堂课:
public class FeedRetrieverSection : ConfigurationSection
{
[ConfigurationProperty("feeds", IsDefaultCollection =
public FeedElementCollection Feeds
{
get { return (FeedElementCollection)this["feeds"]; }
set { this["feeds"] = value; }
}
}
我看到如何使用基于_Config声明的“for each”来迭代它:
public static FeedRetrieverSection _Config =
ConfigurationManager.GetSection("feedRetriever") as FeedRetrieverSection;
我无法弄清楚:如何搜索集合中的给定名称?
使用_Config的声明,如上所示,我想使用linq或字典从<feeds>
列表中获取单个“记录”?
完整筹码:
Web配置中包含:
<feedRetriever>
<feeds>
<add name="Nettuts+" url="http://feeds.feedburner.com/nettuts" cache="false"/>
<add name="Jeremy McPeak" url="http://www.wdonline.com/feeds/blog/rss/" />
<add name="Nicholas C. Zakas" url="http://feeds.nczonline.net/blog/" />
</feeds>
</feedRetriever>
代码用这种方式表示:
public class FeedElement : ConfigurationElement
{
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}
// etc for all of the elements...
}
它包含在ConfigurationElementCollection中,如下所示:
[ConfigurationCollection(typeof(FeedElement))]
public class FeedElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new FeedElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((FeedElement)element).Name;
}
}
答案 0 :(得分:2)
FeedElementCollection
是一个非通用集合,其中包含FeedElement
个。要在其上使用LINQ,您需要使用OfType<>或Cast<>
方法使其“通用”。然后你可以进行过滤:
_Config.Feeds.OfType<FeedElement>().Where(e => e.Name == "Jeremy McPeak");