score:3
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.
- parse your data to split it into atomical values (in this case
int
andstring
) - put the values into a designated structure that fits your needs (here it is simply the attribute
name
). - assemble the data objects in a approriate container class (like
list`1
ordictionary`2
) - if it isn't sorted, sort it; you may need to let your data structure/class implement
icomparable`1
/icomparable
or define a customicomparer`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:
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.
Source: stackoverflow.com
Related Query
- OrderBy numbers that are strings (cannot convert to int)
- Cannot convert source type system.nullable to target type int
- List.Orderby in C# first orderby numbers that are even asc then same number that are odd decending
- Orderby string but that values are numbers (double)
- EF code first cannot convert type to int
- Sum any strings that are numbers from string array using LINQ
- Orderby not ordering strings that include numbers in Linq
- How are people unit testing code that uses Linq to SQL
- Cannot convert lambda expression to type 'string' because it is not a delegate type - OrderBy and DbGeography by ref
- linq - how do you do a query for items in one query source that are not in another one?
- Cannot convert source type to target type List<KeyValuePair> Linq
- The given value of type String from the data source cannot be converted to type int of the specified target column
- How can I check that a sequence of indices of type int are contiguous?
- Linq select all numbers that are in any interval from another list of intervals
- Cannot convert lambda expression to type int because it is not a delegate type
- How to select int that are not in some other list ?
- Convert code that uses Linq to code that does not
- dynamic linq query - OrderBy with properties that are null
- Error on using count method in linq cannot to implecitly convert int to bool
- Cannot convert type bool to int
- Finding strings that are not in DB already
- Convert SQL Server query to LINQ lambda query for two different cols from two different table that are related
- Cannot implicitly convert type decimal? to OrdersList, are you missing a cast
- Linq to Entitites query cannot convert Int to String
- Cannot Implicity convert IEnumerable<int> to int Linq Query
- How to return strings that are sorted by their number(using Linq) in c#
- Cannot convert source type 'System Linq IQueryable<decimal>' to target type decimal
- Comparing two arrays in C# and printing the numbers that are missing
- Entity Framework 4: SQL to Linq: How to select strings that are not uppercase?
- Cannot implilcitly convert type int? to int when retrieving and int field value from LINQ expression
More Query from same tag
- Building a custom|progressive query in LINQ?
- how to get data from datatable by ( select and Group By)
- Cross table / object update with (Db)LINQ
- Error when splitting and replacing chars C# email with LINQ Array Index not supported in LINQ
- Can I populate a list of my own class directly in LINQ?
- LINQ query is not returning expected results
- Entity Framework include collection/reference where
- When does LINQ build its "ON" condition objects?
- read xml file by linq
- Performace Optimization for Comparing an Object to it's Own Table
- Linq query to get per day status of a month
- What's the best way to handle one-to-one relationships in SQL?
- LINQ: How to filter collection by data in related table
- Linq Join issue in C#
- Find objects in list where all properties exists in another list
- Linq query filter with “contains” with list<T> multiple properties
- Inserting XML to XMLDocument
- List<T>.ForEach vs. custom IEnumerable<T> extension
- Windows Phone 7 - App.ViewModel duplicates
- PagedList in asp.net mvc 3 not returning anything to any page after 1
- Entity framework calculated field by Expression<Func<T,V>>
- Two arrays into one Dictionary
- Using the like keyword with linq
- Linq - where condition on child table
- Improve Reused on data filtering code
- Using ==Null in Linq not working to find null values
- C# SQL query blocks server memory
- Which use of Linq Any() is more efficient?
- Linq - Top value from each group
- Problems with casting LinQ result to strongly typed collection