c# - List Sorting numbers in Descending Order -


i have list not sorting @ all. used .sort , not working. want numbers sort in descending order. 9,6,4,3,2

 list<string> tem = new list<string>();  using (sqlconnection cs = new sqlconnection(connstr))  {        cs.open();         (int x = 0; x < length; x++)        {            sqlcommand select = new sqlcommand("spticketissuance_gettransactions", cs);                 select.commandtype = system.data.commandtype.storedprocedure;                 select.parameters.addwithvalue("@transdesc", transtype[x]);              sqldatareader dr = select.executereader();              while (dr.read())             {                 tem.add(dr["transtime"].tostring()); //adds transaction in multiline textbox , adds them list  translist             }             dr.close();        }             tem.sort(); //not sorting             cs.close();         } 

you you're sorting numbers, list contains strings. sorting numerical values in strings lead sorts of weird results if numbers have differing numbers of digits.

this problem sample gave in comment. string sort compares first character (digit) , sees 1 < 2, sorts 12 before 2. if started "2", "12", "7", you'd see produce same result - "12", "2", "7".

if you're storing numeric values, use numeric type list.

also, sort() sort in ascending order. if want produce descending result you'd either need reverse() result, or, other answers have said, use orderbydescending(x => x) instead of sort(). latter option more efficient.

update

i take comment on @steve's answer data type in database character type well?

for text box can like:

string[] lines = text.split(environment.newline, stringsplitoptions.removeemptyentries); list<int> trans = lines.select(line => int32.parse(line)).tolist(); 

the second line blow if entries aren't purely numerical, though. safer way this:

ienumerable<int?> values = lines.select(line =>  {     int value;      return int32.tryparse(line, out value) ? (int?)value : null; }) list<int> trans = values.where(v => v.hasvalue).select(v => v.value).tolist(); 

this discard lines can't converted int.

once you've got data in numeric format, store in database way, , rest of processing (sorting, etc) becomes lot easier.

update 2

like said in comment, orderbydescending() method doesn't change list it's applied to, provides different enumeration order on list. if need results in list add tolist() that. so:

list<int> sortedtrans = transint.orderbydescending(x => x).tolist(); 

Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -