c# - Linq OrderBy Attribute Value and Group -


i have table headers read in db using linq in c#. of these headers, there @ least 1 same; total , want on right.

so here sort of how data laid out:

data {    label,    value,    age  //not used } 

sample data:

{"dog", 7} {"cat", 3} {"other", 4} {"total", 14} 

i'd order labels in order; actual animal names sorted value in descending order , total appended end:

"dog", "other", "cat", "total" 

how do in linq. how order attribute based upon value of attribute?

once have order of headers, there easy way order future rows based upon determined order. if want find headers where(x=>x.age > 20) how can sort labels in where(x=>x.age <= 20) based upon same ordering >20 set?

this query should work:

var query = row in table             let ignore = row.label == "total"             orderby ignore, row.value descending             select row.label;  //and corresponding lambda version var lquery = table.orderby(row => row.label == "total")                   .thenbydescending(row => row.value)                   .select(row => row.label); 

note: isn't entirely necessary create ignore variable, placed directly in orderby clause. way, makes more readable.

not sure asking in second question.


edit:
in response comment, depend on how wanted sorting work, @ least written this. works if there 1 row in table want ignore. not if had more one. problem being among "ignored" rows, sorted original sorting (in case, value). naive way add row add ignore condition.

var query = row in table             let ignore = row.label == "total" || row.label == "cost"             orderby ignore, row.value descending             select row.label; 

to have specific ordering among "ignored" rows, require more complex query:

var query = row in table             let ignore = row.label == "total" || row.label == "cost"             let ignoreorder = row.label == "cost" ? 1 : 0             orderby ignore, ignoreorder, row.value descending             select row.label;  //and corresponding lambda version var lquery = table.orderby(row => row.label == "total" || row.label == "cost")                   .thenby(row => row.label == "cost" ? 1 : 0)                   .thenbydescending(row => row.value)                   .select(row => row.label); 

Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -