我有一串逗号分隔的ID。
(通过SQL SP)我正在检索值以填充List of Class" ProductInfo"它具有ID属性和Name属性。
填充List后,我想根据原始字符串顺序按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
答案 0 :(得分:2)
这是你用神级语言做的。
var sortedList = strIds.Select(x => Products.FirstOrDefault(y => y.ID == x));
我不熟悉你的野蛮脚本,但你可以翻译。
注意,最好使用ID数组而不是逗号分隔列表。
var strIds = new[] {"56312", "73446", "129873", "49879", "38979", };
使代码更容易使用。
马克非常友好地为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))
答案 1 :(得分:1)
继续使用Products.Sort
的概念用法,尝试使用带有Comparison<T>
代表的重载。
首先将id字符串拆分为数组。
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
字符串中的顺序。