提供者集合到字典
我已经实现了提供程序模式并创建了一个在我的项目中使用的提供程序集合。 我需要对我拥有的提供商列表中的某个属性执行搜索以获得特定值。我想知道是否有一种方法可以以优雅的方式将提供者集合转换为字典?有了字典,我可以使用 find 来匹配值。寻找字典或者也许有更好的方法来处理这种情况,而不是执行基本的 foreach 循环。所有帮助并非常感谢。前任。会有帮助的。
谢谢, DND
有没有更好、更简洁的方法来编写这个搜索代码???我正在考虑使用约翰在下面向我展示的字典。你怎么认为?
var ProdNumVal = from p in xdoc.Root.Element("ClientOrderId").Elements()
where (string)p.Attribute("name") == "ProductNumber"
select (string)p.Value;
if (!string.IsNullOrEmpty(ProdNumVal.ToString()))
{
foreach (XMLProviderBase prov in Providers)
{
products = prov.ProductNumber.Split(';');
foreach (string prod in products)
{
if (prod == ProdNumVal.FirstOrDefault())
return prov;
}
}
}
I've implemented the provider pattern and created a providercollection that I'm using in my project.
I need to implement a search against a property in the list of providers I have for a certain value. I was wondering is there a way to convert the providercollection to a dictionary in an elegant way? With the dictionary I can use find to match value. Looking for a Dictionary or maybe there is a better way to handle this kind of scenario instead of doing a basic foreach loop. All help and greatly appreciated. An Ex. would be helpful.
Thanks,
DND
Is there a better, cleaner way to write this search code??? I was thinking of using a dictionary like John has shown me below. What do you think?
var ProdNumVal = from p in xdoc.Root.Element("ClientOrderId").Elements()
where (string)p.Attribute("name") == "ProductNumber"
select (string)p.Value;
if (!string.IsNullOrEmpty(ProdNumVal.ToString()))
{
foreach (XMLProviderBase prov in Providers)
{
products = prov.ProductNumber.Split(';');
foreach (string prod in products)
{
if (prod == ProdNumVal.FirstOrDefault())
return prov;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是在谈论 System.Configuration.Provider.ProviderCollection 还是您自己的 Provider 集合类?
无论如何,您的 ProviderCollection 是 IEnumerable,您可以使用 LINQ ToDictionary() 方法来生成字典:
ToDictionary() 的第一个参数选择键,第二个参数选择值。在这里,我只是以名称/描述为例(假设 ProviderBase 是元素类型),但您可以选择您需要的任何值。
希望有帮助,
约翰
Are you talking about
System.Configuration.Provider.ProviderCollection
or is this your own Provider collection class?In any case, your ProviderCollection is an IEnumerable, you can use the LINQ ToDictionary() method to generate the dictionary:
The first arg to ToDictionary() selects the key, the 2nd arg selects the value. Here, I'm just grabbing Name/Description for an example (assuming ProviderBase is the element type), but you can pick whatever values you need.
Hope that helps,
John