Python sort by enum

How to sort arraylist using enum type

Solution 1: Here is version with custom attribute: Usage: Solution 2: Short Answer: Reason: Output: IMPORTANT NOTES: is backed by some cache since .NET 2.0 (read this nice post about it) and may not return the fields in declared order (more precisely: the order emited by compiler wich seems to preserve the order in one file, but order of merged is undefined). This may be solution for .NET 4.5 Solution:Clarification from comment: Since is an (not ), it is automatically , so to add a secondary sort order by status, you call : Or, if you want to sort the status in ascending order:

Sort an enumerated list by the value [duplicate]

>>> list2 = sorted(list1, key=lambda x:x[1]) >>> list2 [(0, 2), (1, 5), (4, 9), (3, 23), (2, 46), (5, 78)] 
>>> from operator import itemgetter >>> sorted(list1, key=itemgetter(1)) [(0, 2), (1, 5), (4, 9), (3, 23), (2, 46), (5, 78)] 

By providing a function of one argument to key we are specifying a comparison key for list elements used by sorted . itemgetter is a nice functional wrapper around item getter operator [i] .

You need to pass in the whole list (not just the first element), and use a lambda function to sort on the value — x[1] .

>>> list1 = [2,5,46,23,9,78] >>> list2 = list(enumerate(list1)) >>> list2 [(0, 2), (1, 5), (2, 46), (3, 23), (4, 9), (5, 78)] >>> list3 = sorted(list2, key=lambda x: x[1]) >>> list3 [(0, 2), (1, 5), (4, 9), (3, 23), (2, 46), (5, 78)] 

Swift — How to sort objects by its enum value?, Sorted by: 46. Implement the Comparable protocol on your enum. It gives you a static func < (lhs: Difficulty, rhs: Difficulty) ->Bool method where you define the sort. Here is a full sample using a property to simplify the ordering. enum Difficulty: String, Comparable < case easy = "easy" case moderate = "moderate" … Code samplestatic func <(lhs: Difficulty, rhs: Difficulty) ->Bool Feedback

Читайте также:  Java empty stack util

How to sort arraylist using enum type

You should add a compareTo() method on the Card which sorts first by Rank , and if Rank is equal, then by Suit . If we use Guava, it’s very simple:

public class Card implements Comparable  < private Rank rank; private Suit suit; . public int compareTo(Card that) < return ComparisonChain.start() .compare(this.rank, that.rank) .compare(this.suit, that.suit) .result(); >> 

Here’s the Javadoc for ComparisonChain .

If we assume that a hand is a List , then you can sort your list using Collections.sort(hand) .

Java Sorting based on Enum constants, Sorted by: 104. Enum implements Comparable via the natural order of the enum (the order in which the values are declared). If you just create a list of the enum values (instead of strings) via parsing, then sort that list using Collections.sort, it should sort the way you want. If you need a list of strings …

Sort enums in declaration order

Here is version with custom attribute:

[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] public class EnumOrderAttribute : Attribute < public int Order < get; set; >> public static class EnumExtenstions < public static IEnumerableGetWithOrder(this Enum enumVal) < return enumVal.GetType().GetWithOrder(); >public static IEnumerable GetWithOrder(this Type type) < if (!type.IsEnum) < throw new ArgumentException("Type must be an enum"); >// caching for result could be useful return type.GetFields() .Where(field => field.IsStatic) .Select(field => new < field, attribute = field.GetCustomAttribute() >) .Select(fieldInfo => new < name = fieldInfo.field.Name, order = fieldInfo.attribute != null ? fieldInfo.attribute.Order : 0 >) .OrderBy(field => field.order) .Select(field => field.name); > > 
public enum TestEnum < [EnumOrder(Order=2)] Second = 1, [EnumOrder(Order=1)] First = 4, [EnumOrder(Order=3)] Third = 0 >var names = typeof(TestEnum).GetWithOrder(); var names = TestEnum.First.GetWithOrder(); 

Short Answer:

foreach(FieldInfo fi in typeof(CurrencyId).GetFields() .Where(fi => fi.IsStatic).OrderBy(fi => fi.MetadataToken)) Console.WriteLine(fi.Name); 
public enum EnumOrder < Bad = -1, Zero = 0, One = 1 >public class ClassOrder < public int first; public int First < get < return first; >> public int second; public int Second < get < return second; >> > private void PrintInfos(string head, IEnumerable list) where T: MemberInfo < memo.AppendText(string.Format(" : ", head)); bool first = true; foreach(var e in list) < if(first) first = false; else memo.AppendText(", "); memo.AppendText(e.Name); >memo.AppendText("\r\n"); > private void ReflectionOrderTest(object sender, EventArgs e) < typeof(EnumOrder).GetField("One"); typeof(ClassOrder).GetField("second"); typeof(ClassOrder).GetProperty("Second"); memo.AppendLine("First time order:"); PrintInfos("Enum", typeof(EnumOrder).GetFields().Where(fi =>fi.IsStatic)); PrintInfos("Fields", typeof(ClassOrder).GetFields()); PrintInfos("Properties", typeof(ClassOrder).GetProperties()); PrintInfos("Members", typeof(ClassOrder).GetMembers()); memo.AppendLine("Broken order:"); PrintInfos("Enum", typeof(EnumOrder).GetFields().Where(fi => fi.IsStatic)); PrintInfos("Fields", typeof(ClassOrder).GetFields()); PrintInfos("Properties", typeof(ClassOrder).GetProperties()); PrintInfos("Members", typeof(ClassOrder).GetMembers()); memo.AppendLine("MetadataToken Sorted:"); PrintInfos("Enum", typeof(EnumOrder).GetFields().Where(fi => fi.IsStatic).OrderBy(fi => fi.MetadataToken)); PrintInfos("Fields", typeof(ClassOrder).GetFields().OrderBy(fi => fi.MetadataToken)); PrintInfos("Properties", typeof(ClassOrder).GetProperties().OrderBy(fi => fi.MetadataToken)); PrintInfos("Members", typeof(ClassOrder).GetMembers().OrderBy(fi => fi.MetadataToken)); > 
First time order: Enum: Bad, Zero, One Fields: first, second Properties: First, Second Members: get_First, get_Second, ToString, Equals, GetHashCode, GetType, .ctor, Second, First, second, first Broken order: Enum: One, Bad, Zero Fields: second, first Properties: Second, First Members: get_Second, get_First, ToString, Equals, GetHashCode, GetType, .ctor, Second, First, second, first MetadataToken Sorted: Enum: Bad, Zero, One Fields: first, second Properties: First, Second Members: first, second, ToString, Equals, GetHashCode, GetType, get_First, get_Second, .ctor, First, Second

IMPORTANT NOTES: MemberInfo.GetFields() is backed by some cache since .NET 2.0 (read this nice post about it) and may not return the fields in declared order (more precisely: the order emited by compiler wich seems to preserve the order in one file, but order of merged partial class is undefined). Here is similar question on stackoverflow, and one comment from Marc Gravell reads:

10.2.6 Members [. ] The ordering of members within a type is rarely significant to C# code, but may be significant when interfacing with other languages and environments. In these cases, the ordering of members within a type declared in multiple parts is undefined.

Doing this should overcome the problem with the cache:

GC.Collect(); GC.WaitForPendingFinalizers(); var fields = typeof(Whatever).GetFields(); 

Sorting by MetadataToken may help as well. Didn’t find a guarantee, but thisshould provide good reasoning why it should work:

The lower three bytes, referred to as the record identifier (RID), contain the index of the row within the metadata table to which the token’s MSB refers. For example, the metadata token with value 0x02000007 refers to row 7 in the TypeDef table in the current scope. Similarly, token 0x0400001A refers to row 26 (decimal) in the FieldDef table in the current scope.

ORIGINAL ANSWER: Use typeof(CurrencyId).GetFields() , check for FieldInfo.IsStatic (one __value won’t be), then use FieldInfo.Name or GetValue as needed.

Link to IDEONE: http://ideone.com/hnT6YL

using System; using System.Reflection; public class Test < public enum CurrencyId < USD = 840, UAH = 980, RUR = 643, EUR = 978, KZT = 398, UNSUPPORTED = 0 >public static void Main() < foreach(FieldInfo fi in typeof(CurrencyId).GetFields()) if(fi.IsStatic) Console.WriteLine(fi.Name); >> 
USD UAH RUR EUR KZT UNSUPPORTED 

EDIT: The order is not guaranteed 🙁 (See comments)

The GetFields method does not return fields in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which fields are returned, because that order varies.

This may be solution for .NET 4.5

using System; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = false)] public sealed class OrderAttribute : Attribute < private readonly int order_; public OrderAttribute( [CallerLineNumber] int order = 0) < order_ = order; >public int Order < get < return order_; >> > public class Test < public enum CurrencyId < [Order] USD = 840, [Order] UAH = 980, [Order] RUR = 643, [Order] EUR = 978, [Order] KZT = 398, [Order] UNSUPPORTED = 0 >public static void Main() < foreach(FieldInfo fi in typeof(CurrencyId).GetFields() .Where(fi =>fi.IsStatic) .OrderBy(fi => ((OrderAttribute)fi.GetCustomAttributes( typeof(OrderAttribute), true)[0]).Order)) Console.WriteLine(fi.GetValue(null).ToString()); > > 

How to sort an array using values from an enum?, If you use a non-const enum with numeric values you can access the string names and the value. So the second example where val is the value and Order[val] is the name. When using a const enum every use gets replaced with a literal value, so there isn’t anywhere to store another value except in a separate …

How to sort a list by an attribute of its child object?

Clarification from comment:

First course in the list of his courses can be considered his primary subject.

Since CourseStatus is an enum (not Enum ), it is automatically Comparable , so to add a secondary sort order by status, you call thenComparing() :

// ORDER BY courseStartedDate DESC, course[0].courseStatus DESC studentList.sort(Comparator.comparing(Student::getCourseStartedDate) .thenComparing(s -> s.getCourse().get(0).getCourseStatus()) .reversed()); 

Or, if you want to sort the status in ascending order:

// ORDER BY courseStartedDate DESC, course[0].courseStatus ASC studentList.sort(Comparator.comparing(Student::getCourseStartedDate) .reversed() .thenComparing(s -> s.getCourse().get(0).getCourseStatus())); 

Sorting — C# Sort List by Enum, I have got a list of Entity, which has got an enum. public class Car < public int CarId < get; set; >public string CarName < get; set; >public CarCategory CarCategory < get; set; >> public enum CarCategory < None = 0, kLowRange = 1, kMidRange = 2, kHighRange = 3 >

Источник

Python sort by simple enum-like feld

I want to let a user manipulate a (not really big, ~800 data rows) data collection, and let them apply filter/sorts like one would do on Excel. I am reading data from a csv, with the following structure

Program | Mesh | Degree | Proc | Min | Max | Average | Status ------------------------------------------------------------- 'prog1' | 4x4x4| 2x2x2 | 2x1x1| 3.52| 3.8 | 3.72 | 'ok' 'prog2' | 8x4x4| 2x2x2 | 2x2x1| 3.60| 3.9 | 3.80 | 'Warning. ' 

Suppose I have already filtered my list how and I need to sort by ‘Proc’, how would I do that ? The proc column is actually a «string» of enum-like values

There are not so many «enum» values, but I still don’t feel like having a switch. I thought maybe I could actually convert them to integer (by executing the multiplication), but then I lose the «label» (In my graphs I’d want to display that «axbxc») My top goal is to define a top level function «sort_data» where one can provide as argument an arbitrary number of column headers, and the program should sort accordingly eg.

sort_data('proc') # => Sort data per Proc column (axbxc values) sort_data('proc', 'mesh') # => Sort data per proc and then by mesh (axbxc) 

Since the dataset isn’t that big and for non-real time computation, I’m more in favor of readable solutions than efficient (performance wise) EDIT : for filtering I have something like that

def filter_program: self.filtered = [sample for sample in self.data_pointer if sample.program == program] # similar for all columns, except the `if` clause gets more complicated # (I have the code, no problem on those ones) def filter(self, filter_dict): """Execute several filters.""" for header, value in filter_dict.iteritems(): if header in self.headers(): getattr(self, 'filter_'+header)(value) self.active_filters[header] = value else: print('ERROR : unknown filter ' + column + ' (previous filters applied)') return self.filtered 

Writing the filter method was easy since we can apply filters one after another. For sorting it’s a bit more complicated since we want to passe a tuple to the sort method (sort by tuple[0] then by tuple[1]. ), and that those sort functions need to be able to sort the dimension ‘1x1x1’, etc).

def sort(self, sort_dict): for header, value in sort_dict.iteritems(): if !(header in self.headers()): # error return self.sorted = sorted(self.filtered, key=lambda row: (### . ###) 

The code for the key lambda of sort must be a tuple that akes into account all sort criteria of sort_dict. If I wanted to sort by min/average, I’d do

# sort_order = ['min', 'max'] sorted(self.filtered, key=lambda row: (float(row.min), float(row.max)) 
sort_order([ 'mesh' # 1x1x1 then 2x1x1 then 2x2x1 . 'program' # 'alphabetical': prog1 then prog2 . >) 

Источник

Оцените статью