我想按存储的关键字对文章进行分类。我有一个类别的关键字列表,并且我想要一篇文章分配一个关键字数最多的类别。如何对非唯一值列表中的对象进行排序?
For Each keyword As String In category.Keywords
category.tempCount += Regex.Matches(article.Item("title").InnerXml, Regex.Escape(keyword)).Count
category.tempCount += Regex.Matches(article.Item("description").InnerXml, Regex.Escape(keyword)).Count
Next
这是为每个类别完成的,为每篇文章运行。我试图对这个列表进行排序,以便告诉哪个类别是最适合这篇文章的类别。然而,有可能不止一个类别是最好的,而且这些类别都不适合。所以运行这个对我没有帮助:
Categories.Sort(
Function(article1 As ArticleCategory, article2 As ArticleCategory)
Return article1.tempCount.CompareTo(article2.tempCount)
End Function)
也许我这样做都是错的,但到目前为止,我认为我是在正确的道路上。 (我也有一个类别类的默认比较,它只是没有工作。)
我得到最有可能造成的排序异常,因为它们不是唯一的。
我得到的异常是InvalidOperationException:无法比较数组中的两个元素。这是用我建于ArticleClass
Imports System.Xml
Class ArticleCategory
Implements IComparer(Of ArticleCategory)
Public ReadOnly key As Int32
Public ReadOnly Name As String
Public ReadOnly Keywords As List(Of String)
Public tempCount As Integer = 0
Public Sub New(ByVal category As XmlElement)
key = System.Web.HttpUtility.UrlDecode(category.Item("ckey").InnerXml)
Name = System.Web.HttpUtility.UrlDecode(category.Item("name").InnerXml)
Dim tKeywords As Array = System.Web.HttpUtility.UrlDecode(category.Item("keywords").InnerXml).Split(",")
Dim nKeywords As New List(Of String)
For Each keyword As String In tKeywords
If Not keyword.Trim = "" Then
nKeywords.Add(keyword.Trim)
End If
Next
Keywords = nKeywords
End Sub
'This should be removed if your using my solution.
Public Function Compare(ByVal x As ArticleCategory, ByVal y As ArticleCategory) As Integer Implements System.Collections.Generic.IComparer(Of ArticleCategory).Compare
Return String.Compare(x.tempCount, y.tempCount)
End Function
End Class
可能工作...虽然我使用LINQ做我现在整理。非常容易使用,不需要使用比较器的东西。 – JustinKaz 2011-12-19 01:26:00