2012-08-29 36 views
0

我在我的app.config中有一个ConfigurationSection,其中包含一个http端点列表(〜50)。每个人都有一个可选的优先级(以及默认)。将对象集合投射到IEnumerable(类型)

我想按顺序显示此列表。

Dim Config As MyConfigSection = DirectCast(System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None).Sections("MySection"), MyConfigSection) 
Dim Endpoints = MyConfigSection.InitialEndpoints 

在这种情况下InitialEndpointsEndpointcollection类型的继承ConfigurationElementCollection,并且只需收集诺迪这是弱类型的。

端点收集正好对付EndpointDefinition S的依次有UrlPriority等..

我希望能够做到......

For Each E in Endpoints.OrderBy(function(x) x.Priority) 
    ... 
Next 

待办事项我真的需要创建一个新的列表/集合,并将对象转移到对象上,并且随着我的行为进行投射?

作弊和铸造的集合作为IEnumerable导致了无效的转换(并非完全出乎意料)

另一种想法是做类似的东西...

Endpoints.Select(function(x) DirectCast(x, Endpointdefinition)).OrderBy(...) 

EndpointCollection不是列表,因此不会从LINQ Select()扩展中受益。我始终可以实施IList,但现在感觉就像我用大锤打破坚果。

有人可以指出明显的方式来做到这一点吗?作为参考,我EndpointCollection低于

<ConfigurationCollection(GetType(EndpointDefinition), AddItemName:="Endpoint")> 
    Public Class EndpointCollection 
     Inherits ConfigurationElementCollection 

     Protected Overloads Overrides Function CreateNewElement() As ConfigurationElement 
      Return New EndpointDefinition 
     End Function 

     Protected Overrides Function CreateNewElement(elementName As String) As ConfigurationElement 
      Return New EndpointDefinition With {.Url = elementName} 
     End Function 

     Protected Overrides Function GetElementKey(element As ConfigurationElement) As Object 
      Return DirectCast(element, EndpointDefinition).Url 
     End Function 

     Public Overrides ReadOnly Property CollectionType As ConfigurationElementCollectionType 
      Get 
       Return ConfigurationElementCollectionType.AddRemoveClearMap 
      End Get 
     End Property 

     Public Shadows Property Item(index As Integer) As EndpointDefinition 
      Get 
       Return CType(BaseGet(index), EndpointDefinition) 
      End Get 
      Set(value As EndpointDefinition) 
       If Not (BaseGet(index) Is Nothing) Then 
        BaseRemoveAt(index) 
       End If 
       BaseAdd(index, value) 
      End Set 
     End Property 
    End Class 
+1

大多数集合执行'IEnumerable',这是什么'LINQ'其上定义 - 你应该能够只需在集合上直接使用['Cast'](http://msdn.microsoft.com/zh-cn/library/bb341406.aspx)。 – Oded

+0

我应该但抛出一个'源不是IEnumerable <>'ArgumentException – Basic

回答

3

你的问题就在这里是你的类实现IEnumerable,而不是IEnumerable(Of T)

由于EndpointCollection继承ConfigurationElementCollectionConfigurationElementCollection工具IEnumerable,您可以使用OfType()扩展方法(或Cast(),如果你想)。

所以,你应该能够做到以下几点:

Dim Endpoints = MyConfigSection.InitialEndpoints.OfType(Of Endpointdefinition).OrderBy(function(x) x.Priority) 

Dim Endpoints = MyConfigSection.InitialEndpoints.Cast(Of Endpointdefinition).OrderBy(function(x) x.Priority) 
+0

完美,正是我在找的,谢谢 - 我知道它必须在那里。我的理解是,这实际上是过滤而不是转换,因为我的所有元素都是相同的类型,它的工作原理是否正确? (我会在超时完成后立即接受) – Basic

+0

是的。 'OfType'过滤你的收藏。在你的情况下,你可以使用'Cast'来代替。 – sloth