I want to check the age of person by passing in a delegate type in a method and iterating through list.
If i find that person is a child....I want to remove him from the list...because i already performed a test on him and don't want to perform test again.
But i am getting exception after i am remove element from the list...Exception is that i cannot modify the collection during foreach loop.Is there is any way by which i can achieve this because i don't want to perform operation on same person again when age of person is already decided in last operation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DelegateApp
{
/// <summary>
/// A class to define a person
/// </summary>
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
//Our delegate
public delegate bool FilterDelegate(Person p);
static void Main(string[] args)
{
//Create 4 Person objects
Person p1 = new Person() { Name = "John", Age = 41 };
Person p2 = new Person() { Name = "Jane", Age = 69 };
Person p3 = new Person() { Name = "Jake", Age = 12 };
Person p4 = new Person() { Name = "Jessie", Age = 25 };
//Create a list of Person objects and fill it
List<Person> people = new List<Person>() { p1, p2, p3, p4 };
DisplayPeople("Children:", people, IsChild);
DisplayPeople("Adults:", people, IsAdult);
DisplayPeople("Seniors:", people, IsSenior);
Console.Read();
}
/// <summary>
/// A method to filter out the people you need
/// </summary>
/// <param name="people">A list of people</param>
/// <param name="filter">A filter</param>
/// <returns>A filtered list</returns>
static void DisplayPeople(string title, List<Person> people, FilterDelegate filter)
{
Console.WriteLine(title);
foreach (Person p in people)
{
if (filter(p))
{
Console.WriteLine("{0}, {1} years old", p.Name, p.Age);
people.Remove(p);
}
}
Console.Write("\n\n");
}
//==========FILTERS===================
static bool IsChild(Person p)
{
return p.Age <= 18;
}
static bool IsAdult(Person p)
{
return p.Age >= 18;
}
static bool IsSenior(Person p)
{
return p.Age >= 65;
}
}
}
Use a for loop instead of a foreach loop. You can't use foreach loops if you're changing the list as you're looping through it. When using the for loop, you should count backwards through your loop so that you're removing elements from the end.
for (int i = people.Count - 1; i >= 0; i--)
{
Person p = people[i];
if (filter(p))
{
Console.WriteLine("{0}, {1} years old", p.Name, p.Age);
people.RemoveAt(i);
}
}
The reason to go backwards is that otherwise you will skip over some elements. For example, suppose you want to remove elements 4 and 5 of your original list. If you count forwards, then when your loop counter is 4, you'll remove element 4. So then element 5 becomes the new element 4, and element 6 becomes the new element 5. Then on the next iteration of your loop, your counter increments to 5. Now this iteration of the loop is operating on your current element 5 (which was originally your element 6). So your original element 5 got skipped over entirely. Counting backwards avoids this situation. If you were going forward through your list, you'd have to decrement your loop counter each time you removed an element and that's more confusing.
Related
I im currently having an issue with when performing an operation with my structure.
On form load, I am loading a comma delimited file with 6 indexes then using a 2d array i display the structured list's field to a grid view cell.
In the last for loop, perform the operation using my total field?
{
public partial class Form1 : Form
{
public struct Costomers
{
public string firstN;
public string lastN;
public string address;
public string item;
public double price;
public int quantity;
public double total;
}
public Form1()
{
InitializeComponent();
}
List<Costomers> consumers = new List<Costomers>();
private void Form1_Load(object sender, EventArgs e)
{
var inputfile = File.ReadAllLines("customers.txt");
for (int i = 0; i < inputfile.Length; i++)
{
var SplitArr = inputfile[i].Split(',');
// next declare a new instace of costomers
Costomers ConsumerInfo = new Costomers();
// the ConsumerInfo object now contains all of the fields i declared in the structer.
// next i want to access the Objects fields and assign them
ConsumerInfo.firstN = SplitArr[0];
ConsumerInfo.lastN = SplitArr[1];
ConsumerInfo.address = SplitArr[2];
ConsumerInfo.item = SplitArr[3];
ConsumerInfo.price = Convert.ToDouble(SplitArr[4]);
ConsumerInfo.quantity = Convert.ToInt32(SplitArr[5]);
//ConsumerInfo.total = consumers[i].price * consumers[i].quantity;
consumers.Add(ConsumerInfo);
}
// Next i need to disply each field in the grid view
// i will resue my code from section F to do this.
for (int i = 0; i < consumers.Count; i++)
{
dgInfo.Rows.Add();
dgInfo[0, i].Value = consumers[i].firstN;
dgInfo[1, i].Value = consumers[i].lastN;
dgInfo[2, i].Value = consumers[i].address;
dgInfo[3, i].Value = consumers[i].item;
dgInfo[4, i].Value = consumers[i].price;
dgInfo[5, i].Value = consumers[i].quantity;
}
// next in a seperat for loop i need too mutiply the price by the quantity
for (int i = 0; i < consumers.Count; i++)
{
Costomers totalPrice = new Costomers();
totalPrice.total = consumers[i].price * consumers[i].quantity;
dgInfo[6,i].Value = totalPrice.total;
}
}
}
}```
Second, because the file i load does not contain a index for total; how to i display the total in its own column?
Text file as shown below:
The, Batman, 123 Gotham Drive, bat belt, 193.82,17
The, Joker, 12432 Joker Way, Bat Spray, 19.99, 1022
Cat, Women, 8787 Meow St., Kibbles, 9.99, 4700
The, Penguin, 17 Waddel Ave., pointy cigarettes, 24.99, 51700
sidekick, Robin, 123 Gotham Drive, junior bat belt, 67.80, 10000
Adam, West, 1782 Hollywood Dr., hasbeen kit, 10305018.18, 1
Hey ! i am trying to create a program of hospital management system using doubly linked list in c++.
in this i am using whole class for patient data.
i created a nodes for linked list .
i am using one node to represent one bed in hospital.
but after that when i am trying to print some data manually , nothing is printing in console and program is ending without showing any output
this is my code :
#define max_limit 25;// maximum 50 beds can be there in hospital
using namespace std;
class patient //creating class to store the data of patient
{
public:
int pt_id;
string pt_name; //patient name
string diagnosis; //diagnosis patient have
};
struct bed //each bed in hospital
{
class patient p;
struct bed *prev;
struct bed *next;
};
int main()
{
//creating 3 beds in starting only and giving values.
struct bed *head=(struct bed *)malloc(sizeof(patient));
struct bed *second=(struct bed *)malloc(sizeof(patient));
struct bed *tail=(struct bed *)malloc(sizeof(patient));
head->prev=NULL;
head->p.pt_id=6478;
head->p.pt_name="Jayraj";
head->p.diagnosis="Headaches";
head->next=second;
second->prev=head;
second->p.pt_id=8933;
second->p.pt_name="Mayank";
second->p.diagnosis="Highfever";
second->next=tail;
tail->prev=second;
tail->p.pt_id=1788;
tail->p.pt_name="Jay";
tail->p.diagnosis="Stomacheache";
tail->next=NULL;
cout<<"Size:"<<sizeof(patient);
return 0;
}```
You should check the errors - make sure your environment displays them. There are at least these issues:
When allocating a bed you shouldn't use sizeof(patient), but sizeof(bed).
define should not end with a semi-colon.
As a bed could be empty, you'd better define the p member as a pointer to a patient instance
You're not using C++ syntax:
Use new instead of malloc.
Define constructors and methods
Use nullptr instead of NULL
Use PascalCase for class names
Here is some code for inspiration, but you'll need to add more logic to it for your assignment (e.g. you'll have to verify the limit of beds):
#define max_limit 25 // maximum 25 beds allowed in hospital
using namespace std;
class Patient
{
public:
int pt_id;
string pt_name; //patient name
string diagnosis; //diagnosis patient have
// Constructor:
Patient(int id, string name, string diag) :
pt_id(id), pt_name(name), diagnosis(diag) {}
};
class Bed
{
public:
Patient* p = nullptr;
Bed* prev = nullptr;
Bed* next = nullptr;
// Constructors:
Bed() {};
Bed(Patient* p) : p(p) {};
// Method to ease linking beds
Bed* prepend(Bed* other) {
other->next = this;
this->prev = other;
return other;
};
};
int main()
{
// Use constructor to create patients
Patient *jaray = new Patient(6478, "Jayraj", "Headaches");
Patient *mayank = new Patient(8933, "Mayank", "Highfever");
Patient *jay = new Patient(1788, "Jay", "Stomacheache");
// Use constructor and method to create linked list
Bed *beds = (new Bed(jay))
->prepend(new Bed(mayank))
->prepend(new Bed(jaray));
// Let's output something: the beds with patient names
Bed *bed = beds;
while (bed != nullptr) {
if (bed->p == nullptr) {
cout << "bed without patient\n";
} else {
cout << "bed occupied by " << bed->p->pt_name << "\n";
}
bed = bed->next;
}
return 0;
}
In C++, the interface for this file says
*If no soup left returns OUT_OF_SOUP
* If personID not found in my_customers AND numbBowlsSoupLeft>0 then give this person a bowl of soup (return BOWL_OF_SOUP)
* and record it by creating new customer struct using personID, numbBowlsSoup=1 and adding this struct to my_customers, be sure to decrement numbBowlsSoupLeft.
for my implementation, I'm trying to put
int Soupline::getSoup(int personID) {
if (numBowlsSoupLeft == 0) {
return OUT_OF_SOUP;
}
if (!(personID : my_customers) && numbBowlsSoupLeft > 0) {
}
But that second if statement is giving me syntax errros, I just want to know how to check to see if the personID is IN my_customers?
my_customers was created in the soupline interface using:
std::vector<customer> my_customers; // keeps track of customers
First you want to use find() to search a vector.
Second, please handle the case if numbBowlsSoupLeft < 0, because that can be a huge source of problem.
Third, your syntax error is the (personID : my_customers), the : is for iteration.
int Soupline::getSoup(int personID) {
if (numBowlsSoupLeft <= 0) { // handles negative numBowlsSoupLeft
return OUT_OF_SOUP;
}
bool found_customer = false;
for (auto c : my_customers) {
if (personID == c.person_id()) { // This is my guess on how the id is stored in customer class
// Logic to process soup for customer
found_customer = true;
break;
}
}
if (!found_customer) {
// Logic to process non-customer asking for soup?
}
}
Sorry i dunno what is the return integer is supposed to be, so it is not defined in my code example.
How to sort a list of objects by the alphabetical order of one of its properties (Not the name but the actual value the property holds)?
You can pass a comparison function to List.sort.
someObjects.sort((a, b) => a.someProperty.compareTo(b.someProperty));
In general, you can provide a custom comparison function to List.sort.
/// Desired relation | Result
/// -------------------------------------------
/// a < b | Returns a negative value.
/// a == b | Returns 0.
/// a > b | Returns a positive value.
///
int mySortComparison(SomeClass a, SomeClass b) {
final propertyA = someProperty(a);
final propertyB = someProperty(b);
if (propertyA < propertyB) {
return -1;
} else if (propertyA > propertyB) {
return 1;
} else {
return 0;
}
}
list.sort(mySortComparison);
If you're sorting some custom class you own, you alternatively could make your class implement the Comparable interface:
class MyCustomClass implements Comparable<MyCustomClass> {
...
#override
int compareTo(MyCustomClass other) {
if (someProperty < other.someProperty) {
return -1;
} else if (someProperty > other.someProperty) {
return 1;
} else {
return 0;
}
}
}
and then you can use list.sort() directly without supplying a callback.
Note that if you're sorting by a single property that already implements the Comparable interface, implementing the comparison functions is much simpler. For example:
class MyCustomClass implements Comparable<MyCustomClass> {
...
#override
int compareTo(MyCustomClass other) =>
someProperty.compareTo(other.someProperty);
}
Reversing
If you want to reverse the sort order, you can:
Make your comparison function return a value with the opposite sign.
Alternatively just explicitly reverse the list after sorting:
list = (list..sort()).reversed.toList();
Sorting by multiple properties (a.k.a. subsorting)
There are a variety of ways to sort by multiple properties.
A general way is to perform a stable sort for each property in reverse order of importance. For example, if you want to sort names primarily by surname and then subsort within surnames by given name, then you would first sort by given names, and then perform a stable sort by surname. See below for how to perform a stable sort.
Alternatively, you could sort with a comparison function that itself checks multiple properties. For example:
class Name {
Name({String? surname, String? givenName})
: surname = surname ?? "",
givenName = givenName ?? "";
final String surname;
final String givenName;
}
int compareNames(Name name1, Name name2) {
var comparisonResult = name1.surname.compareTo(name2.surname);
if (comparisonResult != 0) {
return comparisonResult;
}
// Surnames are the same, so subsort by given name.
return name1.givenName.compareTo(name2.givenName);
}
package:collection provides an extension to chain comparison functions so that combining them is a bit more straightforward and less error-prone:
import 'package:collection/collection.dart';
int compareSurnames(Name name1, Name name2) =>
name1.surname.compareTo(name2.surname);
int compareGivenNames(Name name1, Name name2) =>
name1.givenName.compareTo(name2.givenName);
final compareNames = compareSurnames.then(compareGivenNames);
My dartbag package also provides a compareIterables function that allows comparing Lists of property values in order of importance:
import 'package:dartbag/collection.dart';
int compareNames(Name name1, Name name2) =>
compareIterables(
[name1.surname, name1.givenName],
[name2.surname, name2.givenName],
);
Okay, I want a stable sort
List.sort is not guaranteed to be a stable sort. If you need a stable sort, package:collection provides insertionSort and mergeSort implementations that are stable.
But comparing might be expensive
Suppose you have a custom comparison function that looks something like:
int compareMyCustomClass(MyCustomClass a, MyCustomClass b) {
var a0 = computeValue(a);
var b0 = computeValue(b);
return a0.compareTo(b0);
}
The sorting process might call computeValue multiple times for the same object, which is particularly wasteful if computeValue() is expensive. In such cases, a Schwartzian transform could be faster (at the expense of using more memory). This approach maps your objects to directly sortable keys, sorts those keys, and extracts the original objects. (This is how Python's sort and sorted functions work.)
Here's one possible implementation:
class _SortableKeyPair<T, K extends Comparable<Object>>
implements Comparable<_SortableKeyPair<T, K>> {
_SortableKeyPair(this.original, this.key);
final T original;
final K key;
#override
int compareTo(_SortableKeyPair<T, K> other) => key.compareTo(other.key);
}
/// Returns a sorted *copy* of [items] according to the computed sort key.
List<E> sortedWithKey<E, K extends Comparable<Object>>(
Iterable<E> items,
K Function(E) toKey,
) {
final keyPairs = [
for (var element in items) _SortableKeyPair(element, toKey(element)),
]..sort();
return [
for (var keyPair in keyPairs) keyPair.original,
];
}
void main() {
final list = <MyCustomClass>[ ... ];
final sorted = sortedWithKeys(list, computeValue);
}
My dartbag package provides such a sortWithKey function (and also a sortWithAsyncKey function if the key needs to be generated asynchronously).
If you want to sort the object "objects" by the property "name" do something like this
objects.sort((a, b) {
return a.value['name'].toString().toLowerCase().compareTo(b.value['name'].toString().toLowerCase());
});
Immutable extension sortedBy for List.
extension MyIterable<E> on Iterable<E> {
Iterable<E> sortedBy(Comparable key(E e)) =>
toList()..sort((a, b) => key(a).compareTo(key(b)));
}
And use
list.sortedBy((it) => it.name);
Here is my contribution to this good question. If someone is facing difficulty to understand how the #Nate Bosch answer is working & you want to sort your custom model class list then you can do this way.
1. You have to implement Comparable abstract class in your model class.
It has the method compareTo which you have to override.
For example, I have this StudentMarks model class which has marks property in it.
class StudentMarks implements Comparable {
int marks;
StudentMarks({
this.marks,
});
#override
int compareTo(other) {
if (this.marks == null || other == null) {
return null;
}
if (this.marks < other.marks) {
return 1;
}
if (this.marks > other.marks) {
return -1;
}
if (this.marks == other.marks) {
return 0;
}
return null;
}
}
2. Now you can call compareTo method inside the sort method.
void _sortStudents({bool reversed: false}) {
_students.sort((a, b) {
return a.compareTo(b);
});
if (reversed) {
_students = _students.reversed.toList();
}
setState(() {});
}
Refer to this link you want to know more about the Comparable class
https://api.dart.dev/stable/2.1.0/dart-core/Comparable-class.html
Its worked for me:
myList..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
Using Comparatorfunction, sort Users by id.
Comparator<UserModel> sortById = (a, b) => a.id.compareTo(b.id);
users.sort(sortById);
Now we can sort it in reversed/descending order.
users = users.reversed.toList();
To sort it in reverse order :
list.sort((a, b) {
return b.status.toLowerCase().compareTo(a.status.toLowerCase());
});
What's more, you can use Comparable.compare for more clear, for example:
class _Person {
final int age;
final String name;
_Person({required this.age, required this.name});
}
void _test() {
final array = [
_Person(age: 10, name: 'Dean'),
_Person(age: 20, name: 'Jack'),
_Person(age: 30, name: 'Ben'),
];
// ascend with age
// Dean Jack Ben
array.sort((p1, p2) {
return Comparable.compare(p1.age, p2.age);
});
// decend with age
// Ben Jack Dean
array.sort((p1, p2) {
return Comparable.compare(p2.age, p1.age);
});
// ascend with name
// Ben Dean Jack
array.sort((p1, p2) {
return Comparable.compare(p1.name, p2.name);
});
}
Similar to #pavel-shorokhovs answer, but strongly typed:
extension IterableExtensions<T> on Iterable<T> {
Iterable<T> sortBy<TSelected extends Comparable<TSelected>>(
TSelected Function(T) selector) =>
toList()..sort((a, b) => selector(a).compareTo(selector(b)));
Iterable<T> sortByDescending<TSelected extends Comparable<TSelected>>(
TSelected Function(T) selector) =>
sortBy(selector).toList().reversed;
}
i had fpgrowth machine learning output/result with each element of list contains another list and frequency field i was to sort by frequency in descending order so i used a bit of recursion for that try it might work i know i am late but i am posting maybe someone else could benefit.
sort(List<FrequentItem> fqItems) {
int len = fqItems.length;
if(len==2){
if(fqItems[0].frequency>fqItems[1].frequency){
sortedItems.add(fqItems[0]);
sortedItems.add(fqItems[1]);
}else{
sortedItems.add(fqItems[1]);
sortedItems.add(fqItems[0]);
}
return;
}else{
FrequentItem max = fqItems[0];
int index =0;
for(int i=0;i<len-2;i++){
if(max.frequency<fqItems[i+1].frequency){
max = fqItems[i+1];
index = i+1;
}
}
sortedItems.add(max);
fqItems.removeAt(index);
sort(fqItems);
}
}
Step 1: Add compareTo method to class:
class Student {
String? name;
int? age;
Student({this.name, this.age});
int getAge() {
if (age == null) return 0;
return age!;
}
#override
int compareTo(Student other) {
var a = getAge();
var b = other.getAge();
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
}
}
Step 2: Sorting your list:
By ascending:
studentList.sort((a, b) {
return a.compareTo(b);
});
By descending:
studentList.sort((a, b) {
return b.compareTo(a);
});
How to sort a list of objects by the alphabetical order of one of its properties (Not the name but the actual value the property holds)?
You can pass a comparison function to List.sort.
someObjects.sort((a, b) => a.someProperty.compareTo(b.someProperty));
In general, you can provide a custom comparison function to List.sort.
/// Desired relation | Result
/// -------------------------------------------
/// a < b | Returns a negative value.
/// a == b | Returns 0.
/// a > b | Returns a positive value.
///
int mySortComparison(SomeClass a, SomeClass b) {
final propertyA = someProperty(a);
final propertyB = someProperty(b);
if (propertyA < propertyB) {
return -1;
} else if (propertyA > propertyB) {
return 1;
} else {
return 0;
}
}
list.sort(mySortComparison);
If you're sorting some custom class you own, you alternatively could make your class implement the Comparable interface:
class MyCustomClass implements Comparable<MyCustomClass> {
...
#override
int compareTo(MyCustomClass other) {
if (someProperty < other.someProperty) {
return -1;
} else if (someProperty > other.someProperty) {
return 1;
} else {
return 0;
}
}
}
and then you can use list.sort() directly without supplying a callback.
Note that if you're sorting by a single property that already implements the Comparable interface, implementing the comparison functions is much simpler. For example:
class MyCustomClass implements Comparable<MyCustomClass> {
...
#override
int compareTo(MyCustomClass other) =>
someProperty.compareTo(other.someProperty);
}
Reversing
If you want to reverse the sort order, you can:
Make your comparison function return a value with the opposite sign.
Alternatively just explicitly reverse the list after sorting:
list = (list..sort()).reversed.toList();
Sorting by multiple properties (a.k.a. subsorting)
There are a variety of ways to sort by multiple properties.
A general way is to perform a stable sort for each property in reverse order of importance. For example, if you want to sort names primarily by surname and then subsort within surnames by given name, then you would first sort by given names, and then perform a stable sort by surname. See below for how to perform a stable sort.
Alternatively, you could sort with a comparison function that itself checks multiple properties. For example:
class Name {
Name({String? surname, String? givenName})
: surname = surname ?? "",
givenName = givenName ?? "";
final String surname;
final String givenName;
}
int compareNames(Name name1, Name name2) {
var comparisonResult = name1.surname.compareTo(name2.surname);
if (comparisonResult != 0) {
return comparisonResult;
}
// Surnames are the same, so subsort by given name.
return name1.givenName.compareTo(name2.givenName);
}
package:collection provides an extension to chain comparison functions so that combining them is a bit more straightforward and less error-prone:
import 'package:collection/collection.dart';
int compareSurnames(Name name1, Name name2) =>
name1.surname.compareTo(name2.surname);
int compareGivenNames(Name name1, Name name2) =>
name1.givenName.compareTo(name2.givenName);
final compareNames = compareSurnames.then(compareGivenNames);
My dartbag package also provides a compareIterables function that allows comparing Lists of property values in order of importance:
import 'package:dartbag/collection.dart';
int compareNames(Name name1, Name name2) =>
compareIterables(
[name1.surname, name1.givenName],
[name2.surname, name2.givenName],
);
Okay, I want a stable sort
List.sort is not guaranteed to be a stable sort. If you need a stable sort, package:collection provides insertionSort and mergeSort implementations that are stable.
But comparing might be expensive
Suppose you have a custom comparison function that looks something like:
int compareMyCustomClass(MyCustomClass a, MyCustomClass b) {
var a0 = computeValue(a);
var b0 = computeValue(b);
return a0.compareTo(b0);
}
The sorting process might call computeValue multiple times for the same object, which is particularly wasteful if computeValue() is expensive. In such cases, a Schwartzian transform could be faster (at the expense of using more memory). This approach maps your objects to directly sortable keys, sorts those keys, and extracts the original objects. (This is how Python's sort and sorted functions work.)
Here's one possible implementation:
class _SortableKeyPair<T, K extends Comparable<Object>>
implements Comparable<_SortableKeyPair<T, K>> {
_SortableKeyPair(this.original, this.key);
final T original;
final K key;
#override
int compareTo(_SortableKeyPair<T, K> other) => key.compareTo(other.key);
}
/// Returns a sorted *copy* of [items] according to the computed sort key.
List<E> sortedWithKey<E, K extends Comparable<Object>>(
Iterable<E> items,
K Function(E) toKey,
) {
final keyPairs = [
for (var element in items) _SortableKeyPair(element, toKey(element)),
]..sort();
return [
for (var keyPair in keyPairs) keyPair.original,
];
}
void main() {
final list = <MyCustomClass>[ ... ];
final sorted = sortedWithKeys(list, computeValue);
}
My dartbag package provides such a sortWithKey function (and also a sortWithAsyncKey function if the key needs to be generated asynchronously).
If you want to sort the object "objects" by the property "name" do something like this
objects.sort((a, b) {
return a.value['name'].toString().toLowerCase().compareTo(b.value['name'].toString().toLowerCase());
});
Immutable extension sortedBy for List.
extension MyIterable<E> on Iterable<E> {
Iterable<E> sortedBy(Comparable key(E e)) =>
toList()..sort((a, b) => key(a).compareTo(key(b)));
}
And use
list.sortedBy((it) => it.name);
Here is my contribution to this good question. If someone is facing difficulty to understand how the #Nate Bosch answer is working & you want to sort your custom model class list then you can do this way.
1. You have to implement Comparable abstract class in your model class.
It has the method compareTo which you have to override.
For example, I have this StudentMarks model class which has marks property in it.
class StudentMarks implements Comparable {
int marks;
StudentMarks({
this.marks,
});
#override
int compareTo(other) {
if (this.marks == null || other == null) {
return null;
}
if (this.marks < other.marks) {
return 1;
}
if (this.marks > other.marks) {
return -1;
}
if (this.marks == other.marks) {
return 0;
}
return null;
}
}
2. Now you can call compareTo method inside the sort method.
void _sortStudents({bool reversed: false}) {
_students.sort((a, b) {
return a.compareTo(b);
});
if (reversed) {
_students = _students.reversed.toList();
}
setState(() {});
}
Refer to this link you want to know more about the Comparable class
https://api.dart.dev/stable/2.1.0/dart-core/Comparable-class.html
Its worked for me:
myList..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
Using Comparatorfunction, sort Users by id.
Comparator<UserModel> sortById = (a, b) => a.id.compareTo(b.id);
users.sort(sortById);
Now we can sort it in reversed/descending order.
users = users.reversed.toList();
To sort it in reverse order :
list.sort((a, b) {
return b.status.toLowerCase().compareTo(a.status.toLowerCase());
});
What's more, you can use Comparable.compare for more clear, for example:
class _Person {
final int age;
final String name;
_Person({required this.age, required this.name});
}
void _test() {
final array = [
_Person(age: 10, name: 'Dean'),
_Person(age: 20, name: 'Jack'),
_Person(age: 30, name: 'Ben'),
];
// ascend with age
// Dean Jack Ben
array.sort((p1, p2) {
return Comparable.compare(p1.age, p2.age);
});
// decend with age
// Ben Jack Dean
array.sort((p1, p2) {
return Comparable.compare(p2.age, p1.age);
});
// ascend with name
// Ben Dean Jack
array.sort((p1, p2) {
return Comparable.compare(p1.name, p2.name);
});
}
Similar to #pavel-shorokhovs answer, but strongly typed:
extension IterableExtensions<T> on Iterable<T> {
Iterable<T> sortBy<TSelected extends Comparable<TSelected>>(
TSelected Function(T) selector) =>
toList()..sort((a, b) => selector(a).compareTo(selector(b)));
Iterable<T> sortByDescending<TSelected extends Comparable<TSelected>>(
TSelected Function(T) selector) =>
sortBy(selector).toList().reversed;
}
i had fpgrowth machine learning output/result with each element of list contains another list and frequency field i was to sort by frequency in descending order so i used a bit of recursion for that try it might work i know i am late but i am posting maybe someone else could benefit.
sort(List<FrequentItem> fqItems) {
int len = fqItems.length;
if(len==2){
if(fqItems[0].frequency>fqItems[1].frequency){
sortedItems.add(fqItems[0]);
sortedItems.add(fqItems[1]);
}else{
sortedItems.add(fqItems[1]);
sortedItems.add(fqItems[0]);
}
return;
}else{
FrequentItem max = fqItems[0];
int index =0;
for(int i=0;i<len-2;i++){
if(max.frequency<fqItems[i+1].frequency){
max = fqItems[i+1];
index = i+1;
}
}
sortedItems.add(max);
fqItems.removeAt(index);
sort(fqItems);
}
}
Step 1: Add compareTo method to class:
class Student {
String? name;
int? age;
Student({this.name, this.age});
int getAge() {
if (age == null) return 0;
return age!;
}
#override
int compareTo(Student other) {
var a = getAge();
var b = other.getAge();
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
}
}
Step 2: Sorting your list:
By ascending:
studentList.sort((a, b) {
return a.compareTo(b);
});
By descending:
studentList.sort((a, b) {
return b.compareTo(a);
});