C#でソートリストの代替
-
11-09-2019 - |
質問
私はすべて同じクラス(ColorNum)から、オブジェクトの数を持っている各オブジェクトは、2部材がvariabelsた(m_Colorとm_Number)
例:
ColorNum1(Red,25)
ColorNum2(Blue,5)
ColorNum3(Red,11)
ColorNum4(White,25)
4つのオブジェクトがColorNumListにある
List<ColorNum> ColorNumList = new List<ColorNum>();
今私はmColor =「赤」を持つオブジェクトがトップであるように、リストを注文したいです。 私は、残りのオブジェクトの順序に気をいけない。
私の述語の方法がどのように見えるか?
解決
LINQを使用します:
var sortedRedAtTop =
from col in ColorNumList
order by col.Color == Red ? 1 : 2
select col;
またはリストのソート方法:
ColorNumList.Sort( (x,y) =>
(x.Color == Red ? 1 : 2)-(y.Color == Red ? 1 : 2) );
他のヒント
ColorNumList.Sort((x, y) => x.m_Color == Red ? 1 : (y.m_Color == Red ? -1 : 0));
のhttpを参照してください:// MSDN .microsoft.com / EN-US /ライブラリ/ system.array.sort(VS.71).aspxのの
[C#]パブリック静的ボイドソート(配列、配列、INT、INT、たIComparer);
次の2つのオブジェクトを比較し、一方が他方よりも、より少ない以上であるかどうかを示す値を返す関数を実装する必要があります。
ます。http:// msdn.microsoft.com/en-us/library/system.collections.icomparer.compare(VS.71).aspxする
あなたは、IComparerインターフェイスをimplemenetsクラスを作成する必要があります。
私はC#を使用しますが、ここではVBと同等であるされていません。
クラスColorCompare 実装したIComparer
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
Dim xc As ColorNum = TryCast(x, ColorNum)
Dim yc As ColorNum = TryCast(y, ColorNum)
If x.color = Red Then
Return 1
ElseIf y.color = Red Then
Return -1
Else
Return 0
End If
End Function
End Class
所属していません StackOverflow