列表排序,如果整数相同,则相关字符串应按字母顺序排列,整数值应升序排列
List sorting, if integers are same that related strings should be in alphabetical order and the interger values should be ascending order
Dart 列表应根据元素对象内的相同整数值按字母顺序排序。如果整数具有相同的值,则那些相关的字符串应按字母顺序和升序排列
这是列表。
列表项 = [人( 10 , 'a' ) , 人( 5 , 'c' ), 人( 15 , 'b' ), 人( 15 , 'a' ), 人( 5 , 'k' ), 人( 10 , 'd' ) 人( 7, 'c' )];
预期结果:
列表项 = [人( 5 , 'c' ) , 人( 5 , 'k' ), 人( 7 , 'c' ), 人( 10 , 'a' ), 人( 10 , 'k' ), 人( 15 , 'a' ) 人( 15, 'd' )];
不需要 Jahidul Islam 建议的双重排序。你只需要制作一个比较方法来比较名称,以防数字相同。所以像这样:
void main() {
final items = [
People(10, 'a'),
People(5, 'c'),
People(15, 'b'),
People(15, 'a'),
People(5, 'k'),
People(10, 'd'),
People(7, 'c'),
];
print(items);
// [People(10,'a'), People(5,'c'), People(15,'b'), People(15,'a'), People(5,'k'), People(10,'d'), People(7,'c')]
items.sort((p1, p2) {
final compareAge = p1.age.compareTo(p2.age);
if (compareAge != 0) {
return compareAge;
} else {
return p1.name.compareTo(p2.name);
}
});
print(items);
// [People(5,'c'), People(5,'k'), People(7,'c'), People(10,'a'), People(10,'d'), People(15,'a'), People(15,'b')]
}
class People {
final int age;
final String name;
People(this.age, this.name);
@override
String toString() => "People($age,'$name')";
}
Dart 列表应根据元素对象内的相同整数值按字母顺序排序。如果整数具有相同的值,则那些相关的字符串应按字母顺序和升序排列
这是列表。
列表项 = [人( 10 , 'a' ) , 人( 5 , 'c' ), 人( 15 , 'b' ), 人( 15 , 'a' ), 人( 5 , 'k' ), 人( 10 , 'd' ) 人( 7, 'c' )];
预期结果:
列表项 = [人( 5 , 'c' ) , 人( 5 , 'k' ), 人( 7 , 'c' ), 人( 10 , 'a' ), 人( 10 , 'k' ), 人( 15 , 'a' ) 人( 15, 'd' )];
不需要 Jahidul Islam 建议的双重排序。你只需要制作一个比较方法来比较名称,以防数字相同。所以像这样:
void main() {
final items = [
People(10, 'a'),
People(5, 'c'),
People(15, 'b'),
People(15, 'a'),
People(5, 'k'),
People(10, 'd'),
People(7, 'c'),
];
print(items);
// [People(10,'a'), People(5,'c'), People(15,'b'), People(15,'a'), People(5,'k'), People(10,'d'), People(7,'c')]
items.sort((p1, p2) {
final compareAge = p1.age.compareTo(p2.age);
if (compareAge != 0) {
return compareAge;
} else {
return p1.name.compareTo(p2.name);
}
});
print(items);
// [People(5,'c'), People(5,'k'), People(7,'c'), People(10,'a'), People(10,'d'), People(15,'a'), People(15,'b')]
}
class People {
final int age;
final String name;
People(this.age, this.name);
@override
String toString() => "People($age,'$name')";
}