【问题标题】:Sort List of class by string of ID's按 ID 字符串对类列表进行排序
【发布时间】:2014-06-11 13:40:39
【问题描述】:

我有一串逗号分隔的 ID。

(通过 SQL SP)我正在检索值以填充“ProductInfo”类列表,该列表具有 ID 属性和 Name 属性。

List 填充完毕后,我想按照原来的 Strings 顺序按 ID 对列表进行排序。

用于检索数据的 SP 按 ID ASC 排序,我无法更改 SP。

Public Class ProductInfo
    Private _id as String
    Public Property ID as String
        ..get..
        ..set..
    End Property

    Private _name as String
    Public Property Name as String
        ..get..
        ..set..
    End Property
End Class


Dim strIds as String = "56312,73446,129873,49879,38979"

Dim Products As New List(Of ProductInfo)
Products = FillProductDetails(strIds)

Products.Sort(strIds) ''''Conceptual

【问题讨论】:

  • 我认为如果 ProductInfo 覆盖 .ToString 以返回 ID,那么 Products.Sort() 就是您所需要的。否则,您可能需要提供一个提供排序智能的比较器:Sort(comparer As System.Collections.Generic.IComparer(Of T))
  • 您也可以改用SortedList。问题当然是文本比较器会失败,例如{"9011", "100003"}“9011”将排序高于“1000003”,这是 IComparer 可以处理/转换的。

标签: .net vb.net list sorting


【解决方案1】:

这就是你在神级语言中的做法。

var sortedList = strIds.Select(x => Products.FirstOrDefault(y => y.ID == x));

我不熟悉你的野蛮脚本,但你可能会翻译。

注意,最好使用 ID 数组而不是逗号分隔的列表。

var strIds = new[] {"56312", "73446", "129873", "49879", "38979", };

使其更易于在代码中使用。

Mark 很友好地提供了 Moonspeak 的翻译:

Dim sortedList = strIds.Split(","c).Select(Function(x) Products.FirstOrDefault(Function(y) y.ID = x))

或者,将 strIds 作为一个数组

Dim sortedList = strIds.Select(Function(x) Products.FirstOrDefault(Function(y) y.ID = x))

【讨论】:

  • 您需要拆分strIds,这样您就不会寻找每个字符,但这里是“野蛮”版本:Dim sortedList = strIds.Split(","c).Select(Function(x) Products.FirstOrDefault(Function(y) y.ID = x))
  • @Mark:啊,是的,它不是一个数组。我会澄清的。并感谢您翻译成月语。
  • 这行得通!不知道怎么做,但我会分析这个外星代码来学习它的方法。 +5 神级 -> Moonspeak (@Mark ©)
  • @adam:Select 方法的作用本质上是“对于这个可枚举项中的每个项目,执行用户定义的转换并返回结果”。可枚举的是 ID 列表,每个 ID 都按顺序传递给用户定义的函数。在该函数中,我正在查找具有该 ID 的第一个产品的 Products 并返回它。所以,它通过了 56312,我找到了 ID 为 56312 的产品。然后它通过了 73446,等等等等。
【解决方案2】:

根据您对Products.Sort 的概念用法,这里尝试使用采用Comparison<T> 委托的重载。

先将ids字符串拆分成一个数组。

Dim straIds As String() = strIds.Split(","c)

然后按数组中的位置排序。内联版本:

Products.Sort(Function(x, y) If(Array.IndexOf(straIds, x.Id) > Array.IndexOf(straIds, y.Id), -1, If(Array.IndexOf(straIds, x.Id) = Array.IndexOf(straIds, y.Id), 0, 1)))

或者更易读的版本:

    Products.Sort(Function(x, y) 
                      Dim i As Integer = Array.IndexOf(straIds, x.Id)
                      Dim j As Integer = Array.IndexOf(straIds, y.Id)
                      Return If(i > j, -1, If(i = j, 0, 1))
                  End Function)

不确定它是否会像所写的那样工作,但尝试提供一个Comparison 委托,以保留原始strIds 字符串中的顺序。

【讨论】:

    猜你喜欢
    • 2021-06-10
    • 2014-04-15
    • 2012-04-03
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 2018-07-02
    • 2015-03-26
    相关资源
    最近更新 更多