c# - Does a List do auto sorting? -
i wondering list auto sort or something?
i have
list<myclass> myclass = new list<myclass>() myclass.add(anotherclass); myclass.add(anotherclass2); myclass.add(anotherclass3); myclass.add(anotherclass4); so of them myclass object. have in it
public class myclass { public string type {get; set;} public string title {get; set;} } list<myclass> first = myclass .where(x => x.type == "first").tolist(); list<myclass> second = myclass .where(x => x.type == "second").tolist(); first.sort((x, y) => string.compare(x.title, y.title)); second.sort((x, y) => string.compare(x.title, y.title)); myclass.clear(); myclass.addrange(first); myclass.addrange(second); so real code sort of looks except "myclass" more complex , have them in foreach loop.
when first.sort() , second.sort() objects in correct order based on title. when clear , add "first" objects in first , "second" object second ruins sorting.
i need objects type "first" sorted , before objects types "second".
so have
a - first b - second c - first d - second it be
a c b d i getting
a - first b - second c - first d - second
no, list<t> stores elements in order add them, unless explicitly insert @ particular positions.
you can ask sort, however, , provide custom comparison sort on - have done.
it looks you're doing right thing describe want. if took men in train carriage i'm sitting in, ordered them age, , created 1 list that, did same women, , used:
list<person> allpeople = new list<person>(); allpeople.addrange(mensortedbyage); allpeople.addrange(womensortedbyage); i wouldn't everyone sorted age - i'd men (sorted age) women (sorted age). that's should seeing.
if that's not you're seeing it's want, need give short complete program demonstrates problem. tell expected, , got.
if want order multiple criteria, it's easiest use linq:
var ordered = people.orderby(p => p.gender) .thenby(p => p.age) .tolist(); edit: demonstration of code (fixed typos, , using anonymous type simplicity) working:
using system; using system.collections.generic; using system.linq; class test { static void main() { var myclass = new[] { new { type="first", title="a" }, new { type="second", title="d" }, new { type="first", title="c" }, new { type="second", title="b" }, }.tolist(); var first = myclass.where(x => x.type == "first") .tolist(); var second = myclass.where(x => x.type == "second") .tolist(); first.sort((x, y) => string.compare(x.title, y.title)); second.sort((x, y) => string.compare(x.title, y.title)); myclass.clear(); myclass.addrange(first); myclass.addrange(second); foreach (var x in myclass) { console.writeline(x); } } } output:
{ type = first, title = } { type = first, title = c } { type = second, title = b } { type = second, title = d }
Comments
Post a Comment