包含基本功能的特定类型的集合类

时间:2016-05-01 17:34:02

标签: vb.net

每次我使用某个类别,如Artikel,如下:

Public Class Artikel  
   Property ID As Integer
   Property Nummer As String
   Property Name As String 
   Property Position As Integer
End Class

对于这样的课程,我想要收集课程。我希望拥有的功能如下:

--> Add (passing Artikel object)
--> Remove (passing Artikel object)
--> Sort entire collection (based on Position property desc/asc)
--> Compare two Artikels (pass by Artikels and tell by which property has to be compared)
--> Check whether two artikels equals
--> Every added artikel has to be marked by Key (so maybe dictionary)? <key><Artikel>
--> Remove Artikel (passing by Key index)

你能告诉我或者甚至更好地提供收集课的例子来传递这些要求吗?

编辑:启动:

Artikel的收藏:

Option Strict On
Public Class Articles

Public Property collection As Dictionary(Of Integer, Artikel)

Sub New()
    'Initiate new collection
    collection = New Dictionary(Of Integer, Artikel)
End Sub

   'Add new Artikel to collection
    Public Function AddToCollection(ByVal artikel As Artikel) As Boolean
        collection.Add(artikel)
        Return True
    End Function

    'Remove specific Artikel
    Public Sub RemoveFromCollectionByArtikel(artikel As Artikel)
        If Not IsNothing(collection) Then
            collection.Remove(artikel)
        End If
    End Sub

   'Get collection
   Public Function GetCollection() As Dictionary(Of Integer, Artikel)
        Return collection
    End Function

   'Sort collection by property position
   Public Sub SortByPosition()
        collection.Sort()
    End Sub

    'Remove specific sending keys and then reorder them
    Public Sub RemoveAllMarkedAsDeleted(keys As List(Of Integer))
        '-- Check whther anything has been marked as deleted
        If keys.Count > 0 Then
            For Each row In keys
                collection.Remove(row)
            Next
            ReorderKeys()
    End If

    'Reorder all Artikels in collection
    Private Sub ReorderKeys()
        Dim newCollection As New Dictionary(Of Integer, Artikel)
        Dim index As Integer = 0
        For Each collitem In collection
            newCollection.Add(index, collitem.Value)
            index += 1
        Next
        collection.Clear()
        collection = newCollection
    End Sub


End Class

Artikel类(另外我实现了IComparable以便能够排序)

Option Strict On
     Public Class Artikel   
         Implements IComparable(Of Artikel)
           Property ID As Integer
           Property Nummer As String
           Property Name As String 
           Property Position As Integer

        Public Function CompareTo(pother As Artikel) As Integer Implements IComparable(Of Artikel).CompareTo    'we can sort because of this
            Return String.Compare(Me.Position, pother.Position)
        End Function
        Public Shared Function FindPredicate(ByVal partikel As Artikel) As Predicate(Of Artikel)
            Return Function(partikel2 As Artikel) partikel.ID = partikel2.ID
        End Function
        Public Shared Function FindPredicateByUserId(ByVal partikel As String) As Predicate(Of Artikel)
            Return Function(partikel2 As Artikel) partikel = partikel2.ID
        End Function
    End Class

2 个答案:

答案 0 :(得分:0)

创建班级

sample_submission.csv

创建另一个包含私有列表并向其添加子例程的类

Public Class Artikel  
   Property ID As Integer
   Property Nummer As String
   Property Name As String 
   Property Position As Integer

   sub new (_ID as integer, _Nummer as string, _Name as string, _Position as integer)
      ID = _ID
      Nummer = _Nummer
      Name = _Name
      Position = _Position
   End Sub
End Class

然后使用你的列表类。

 Public Class ArtikelList
      Private _List as new list (of Artikel)

      Public sub remove(Key as integer)
         Dim obj as Artikel = nothing
         for each x as Artikel in _List
            if x.ID = Key then
               obj = x
               exit for
            end if
         Next
         if not isnothing(obj) then
               _List.remove(obj)
          end if
      End sub

      Sub Add(obj as Artikel)
         Dim alreadyDeclared as boolean = falsse

         for each x as Artikel in _List
            if x.ID = obj.id then
               alreadyDeclared = true
               exit for
            end if
         Next
          if not AlreadyDeclared then
               _List.add(obj)
          Else
             'Somehow inform the user of the duplication if need be.
          end if

      End sub
    End Class

我只添加了一个子例程作为示例。我希望它有所帮助,但可以随意提出更多示例例程。

这也可以通过创建一个继承自列表类的类来完成,公开所有列表类功能,但是通过使用此方法,您将被迫创建将要使用的每个子例程。这样,您只能使用专门为Artikel对象处理而创建的例程。

检查两个Artikels是否相等

dim L as new ArtikelList
L.add(new Artikel(1280, "AFKforever!", "Prof.FluffyButton", 96))
L.remove(1280)

使用它像:

Public Class Artikel  
       Property ID As Integer
       Property Nummer As String
       Property Name As String 
       Property Position As Integer

       sub new (_ID as integer, _Nummer as string, _Name as string, _Position as integer)
          ID = _ID
          Nummer = _Nummer
          Name = _Name
          Position = _Position
       End Sub
    End Class

Public Overrides Overloads Function Equals(obj As Object) As Boolean

      If obj Is Nothing OrElse Not Me.GetType() Is obj.GetType() Then
         Return False
      else
        dim _obj as artikel = obj
        if Me.ID = _obj.ID then
           Return true
        else Return False
      End If

   End Function 


End Class 

答案 1 :(得分:0)

部分内容看起来不错,但我最终会做的有点不同。首先,考虑对item类的重载,使它们更容易创建和默认初始化:

Public Class Article
    Property ID As Integer = -1
    Property Key As String = ""
    Property Name As String = ""
    Property Position As Integer = -1
    Property PubDate As DateTime = DateTime.Minimum

    Public Sub New()

    End Sub
    ' whatever minimum data a new item requires
    Public Sub New(k As String, n As String)
        Key = k
        Name = n
    End Sub
    ' full initialization:
    Public Sub New(k As String, n As String, pos As Int32,
                    pubDt As DateTime)
       ...
   End Sub
End Class

我添加了一些属性的属性,我怀疑&#34; Nummer&#34;可能是&#34; Key&#34;在OP中提到,但不管它是什么,如果它具有一定的重要性,我会将它添加到Article作为该名称

您可能需要一个简单的ctor进行序列化(???)。其中一些将找到并使用Private无参数构造函数,但是您的代码将被强制使用其中一个重载,以便在创建新数据时提供一些最低级别的数据。

您可能不需要IComparable。这通常用于更复杂的比较,例如多个或复杂的属性。一个例子是纸箱或盒子:

If (width = Other.Width) AndAlso (height = Other.Height) Then
    Return 0
ElseIf (width = Other.Height) AndAlso (height = Other.Width) Then
    Return 0
End If

还有更多的旋转来解决这个问题,而不是&#34;更少&#34;比另一个。你不需要它的一个原因是因为If Art1.Postion > Art2.Postion是微不足道的。 你的案例中的另一个原因是因为Dictionary无法排序。

而不是Dictionary,内部列表可以更好地处理您描述的某些内容,但仍然允许您将表示为 Dictionary到一定程度你需要它。为此,我可以使用ICollection<T>

构建它
Public Class ArticleCollection
    Implements ICollection(Of Article)

在该行之后按Enter键将添加所有必需的方法,包括:

Public Sub Add(item As Article) Implements ICollection(Of Article).Add

Public Sub Clear() Implements ICollection(Of Article).Clear

Public Function Contains(item As Article) As Boolean Implements ICollection(Of Article).Contains

Public ReadOnly Property Count As Integer Implements ICollection(Of Article).Count

Public Function Remove(item As Article) As Boolean Implements ICollection(Of Article).Remove

完全取决于 这些是如何实现的。它也不排除添加RemoveAt(int32)RemoveByKey(string)等方法,具体取决于您的需求/使用方式。 ICollection(Of T)的一个好处是它包含IEnumerable,允许每个循环使用(一旦你编写枚举器):For Each art In Articles

要模拟字典,只允许一个具有特定属性值的项目:

Public Class ArticleCollection
    Implements ICollection(Of Article)

    Private mcol As List(Of Article)
    ...
    Public Sub Add(item As Article) Implements ICollection(Of Article).Add
        ' check for existing key
        If KeyExists(item.Key) = False Then
            mcol.Add(item)
        End If
    End Sub

你也可以重载它们:

' overload to match Article ctor overload
Public Sub Add(key As String, name As String)
     If KeyExists(key) = False Then
        ' let collection create the new item
        ' with the minimum required info
        mcol.Add(New Article(key, name))
    End If
End Sub

如果添加Item属性,则可以对集合(Articles(3))编制索引:

Property Item(ndx As Int32) As Article
    Get
        If ndx > 0 AndAlso ndx < mcol.Count Then
            Return mcol(ndx)
        Else
            Return Nothing
        End If
    End Get
    Set(value As Article)
        If ndx > 0 AndAlso ndx < mcol.Count Then
            mcol(ndx) = value
        End If
    End Set
End Property

' overload for item by key:
Public Property Item(key As String) As Article

如果集合将显示在标准NET Add中,则Item方法和CollectionEditor属性将非常重要。

有几种方法可以实现排序。最简单的方法是在使用您的集合的代码中使用linq:

Articles = New ArticleCollection
' add Article items
Dim ArticlesByDate = Articles.OrderBy(Function(s) s.PubDate).ToList()

其中PubDate是我添加的Article属性之一。处理排序的另一种方法是通过集合类返回一个新集合(但它很简单,几乎不需要它):

Friend Function GetSortedList(bSortAsc As Boolean) As List(Of Article)
    If bSortAsc Then
        Return mcol.OrderBy(Function(q) q.PubDate).
                ThenBy(Function(j) j.Position).ToList()
    Else
        Return mcol.OrderByDescending(Function(q) q.PubDate).
                ThenByDescending(Function(j) j.Position).ToList()
    End If
End Function

它是否实现ICollection(Of T),继承自ICollection(Of T)还是继承Dictionary完全取决于它是什么,如何使用以及有什么规则和限制(包括它将被序列化,如何)。这些不是我们所知道的。

MSDN上有一篇关于 Guidelines for Collections 的文章优秀