Know that LINQ has an order by function, but still do a bit of hands-on research, it is more practice reflection. This is a note, directly on the code:
Using System;
Using System.Collections.Concurrent;
Using System.Collections.Generic;
Using System.Diagnostics;
Using System.Linq;
Using System.Reflection;
Using System.Security.Cryptography;
Using System.Text;
Using System.Threading.Tasks;
Namespace Testmultiplepropertysort
{
Class Program
{
static void Main (string[] args)
{
#region Simple test data
var list = new List<myclass> ()
{
New MyClass ()
{
P1= "H3",
P2=1,
P3=datetime.now
},
New MyClass ()
{
p1= "H2",
P2=3,
P3=datetime.now.addhours (-1)
},
New MyClass ()
{
P1= "H1",
p2=2,
P3=datetime.now.addhours (1)
},
New MyClass ()
{
P1= "H3",
P2=1,
P3=datetime.now
},
New MyClass ()
{
P1= "H1",
P2=1,
P3=datetime.now
},
New MyClass ()
{
p1= "H2",
p2=2,
P3=datetime.now.addhours (1)
},
};
#endregion
Calling Multi-field ordering
Sortmutiplepropertyhelper<myclass>. Sortmutipleproperty (list);
can be reused
Sortmutiplepropertyhelper<mysecondclass>. Sortmutipleproperty (New list<mysecondclass> ());
Output sort Results
List. ForEach (M = Trace.WriteLine (m.tostring ()));
}
}
public class MyClass
{
[SortOrder (0)]
public string P1 {get; set;}
[SortOrder (1)]
public int P2 {get; set;}
[SortOrder (2)]
Public DateTime P3 {get; set;}
public override string ToString ()
{
Return P1. ToString () + "," + P2. ToString () + "," + P3. ToString ();
}
}
public class Mysecondclass
{
}
[AttributeUsage (Attributetargets.property, AllowMultiple = False, inherited = False)]
public class Sortorderattribute:attribute
{
& nbsp; public int Order {get; set;}
public Sortorderattribute (int order)
{
this. order = order;
}
}
public class sortmutiplepropertyhelper<t> where T:class, new ()
{
<summary>
Dictionary of saving properties and orders
</summary>
public static readonly Dictionary<propertyinfo, sortorderattribute> attrdic = new Dictionary<propertyinfo, Sortorderattribute> ();
Static Sortmutiplepropertyhelper ()
{
Initialize the Order field
Type T = typeof (T);
foreach (Var prop in T.getproperties ())
{
foreach (Var sortorderattribute in Prop. GetCustomAttributes (typeof (Sortorderattribute), false))
{
if (Sortorderattribute is Sortorderattribute)
{
Attrdic.add (prop, sortorderattribute as Sortorderattribute);
Break
}
}
}
}
public static void Sortmutipleproperty (List<t> List)
{
List. Sort ((t1, t2) =
{
int result = 0;
foreach (Var attr in attrdic.orderby (key = = key). Value.order))
{
The simple way to turn attributes into string comparisons is to make different comparisons for different types.
String v1 = attr. Key.getvalue (T1). ToString ();
String v2 = attr. Key.getvalue (T2). ToString ();
result = V1.compareto (v2);
if (Result! = 0)
{
Break
}
}
return result;
});
}
}
}
Multi-attribute ordering of list using custom attributes