score:3

Accepted answer

you can extract the data you want and then do the order by

var sorted = list
    .select(x => new
    {
        splited = x.split(),
        raw = x
    }) //split the string and keep the raw value
    .select(x => new
    {
        count = int.parse(x.splited[0]), // extract the number 
        raw = x.raw
    })
    .orderby(x => x.count) //order by that number
    .select(x => x.raw); //select raw value

score:0

the problem, as you've already identified, is that you cannot orderby the string. you want to sort the list on the numeric part, treated as a number.

we'll tell orderby to order on that part, by splitting the string on the first space, converting the first part parts[0] to an int and sort the list on that value.

no need to use select, storing the original value and such. just a simple orderby on the original list.

namespace sortlisttest1
{
    using system;
    using system.collections.generic;
    using system.linq;

    class program
    {
        static void main(string[] args)
        {
            var animals = new list<string> { "10 dog", "53 cow", "2 crow", "29 horse", "12 rabbit", "107 frog", "35 cat", "7 dragon" };

            var orderedanimals = animals.orderby(
                x =>
                    {
                        var parts = x.split(' '); // split on first space
                        return int.parse(parts[0]); // i.e. the numeric part, cast to an int
                    });

            foreach (var orderedanimal in orderedanimals)
            {
                console.writeline(orderedanimal);
            }
        }
    }
}

2 crow
7 dragon
10 dog
12 rabbit
29 horse
35 cat
53 cow
107 frog
press any key to continue . . .

score:0

i suggest instead of using list of strings use a dictionary. your data structure looks like being in the form of key values.

dictionary<int,string> animals = new dictionary<int,string>();

let the key part take the integer portion and let the string part handle name portion.

then you can easily sort the data structure as below

sortedanimallist = animals.orderbyascending(a => a.key);

score:0

split the string using space as the separator, take the first value and convert it to in int:

sortedlist = sortedlist
    .orderby(g => int32.parse(g.split(' ')[0]))
    .tolist()

score:0

i suggest taking a different approach: you have a list of (count, name) pairs (or (id, name) pairs), where name is your data object and count an quantifier.

  1. parse your data to split it into atomical values (in this case int and string)
  2. put the values into a designated structure that fits your needs (here it is simply the attribute name).
  3. assemble the data objects in a approriate container class (like list`1 or dictionary`2)
  4. if it isn't sorted, sort it; you may need to let your data structure/class implement icomparable`1/icomparable or define a custom icomparer`1.


here is what i came up with:

code:

static void main(string[] args) {
    var unsortedlist = new list<string>() { "10 dog", "53 cow", "2 crow", "29 horse", "12 rabbit", "107 frog", "35 cat", "7 dragon" };
    var sortedlist = new sortedlist<int, string>((int)unsortedlist.count);
    foreach(var entry in unsortedlist) {
        string[] frags = entry.split(' ');
        if(frags.length != 2) {
            throw new formatexception();
        }
        int count = convert.toint32(frags[0]);
        string name = frags[1];
        sortedlist.add(count, name);
    }
    console.writeline("unsorted:");
    unsortedlist.foreach(console.writeline);
    console.writeline();

    console.writeline("sorted:");
    foreach(var entry in sortedlist) {
        console.writeline(entry.key + " " + entry.value);
    }
    console.writeline();
    console.readkey();
}

output: enter image description here

score:0

try this

sortedlist.orderby(g => int.parse(g.split(' ').first())).tolist();

score:1

use these lines for sorting:

list<string> l = new list<string> { "10 dog", "53 cow", "2 crow", "29 horse", "12 rabbit", "107 frog", "35 cat", "7 dragon" };

var sort = from s in l
           orderby convert.toint32(s.split(' ')[0]) 
           select s;

score:1

lst = lst.orderby(x => convert.toint32(x.split()[0])).tolist();

score:1

i know this is not was you asked for. i also see that there are many answer to do exactly what you asked for. this is a suggestion.

i don't know your system or anything but i think here by processing your object as string is an error. i'm pretty sure your system could benefit from having and object rather than this string representing your object. by creating a simple object even such as

public class animal
{
    public string name{ get; set }
    public int index{ get; set; }
}

you would gain type safety at many places. it would become easier to modify (in your current system try to add a third property such as type ["mammal", "reptile", "fish", etc.] and you will understand what i'm talking about). if you need to display that object as the string you have you can always override the tostring() of this object such as described here.

public override string tostring() 
{
    return string.format("{0} {1}", index, name);
}

now when you would need to order or to do any manipulation on your object it become much simpler because you have a regular object not a string containing an object.


Related Query