0

I've a little problem on a LINQ query to group and order my datatable. I'm on a winforms 3.5 project with datagrid control (I know that isn't a very helpful control but i've no choice to change that :( ... unfortunately)

So, How can I make this custom order with LINQ ?

For example :

Name   | Age |
Test     38
Test-1   20
Test-2   18
Test2    40
Test2-1  24
Test2-2  16

Sort by age and keep hierarchy of name

exemple sort by descending

Name   | Age |
Test2    40
Test2-1  24
Test2-2  16
Test     38
Test-1   20
Test-2   18

I need to put the reslut of this query in a datatable to rebind my datagrid!

  • you should be able to create your own comparison function - see http://stackoverflow.com/questions/985657/use-own-icomparert-with-linq-orderby – tofutim Jan 13 '14 at 15:29
  • What does the actual data look like in the database? It's not clear from the example. – Servy Jan 13 '14 at 15:33
  • @tofutim This isn't linq to objects, its querying a database. – Servy Jan 13 '14 at 15:34
  • but you should still be able to do the ordering after the fact with linq – tofutim Jan 13 '14 at 15:35
  • If at all possible you should refactor your database so that you have a "parent" column or something like that, rather than relying on string manipulation to try to figure out which rows are related. – Servy Jan 13 '14 at 15:42
  • Sorry I re-edit my post to make my request more understandable. It's not a LINQ to SQL but directly LINQ on datable bind with my datagrid to make a custom sort – user3190730 Jan 13 '14 at 15:44
  • Your data is not conducive to a good understanding of the required output. – Luc Morin Jan 13 '14 at 22:00
  • In fact, my case is ... I have to "make survive" an old app ... 3.5 with a complexe framework based on a Datagrid and it's too long to rewrite with datagridview ... Now, I have to simulate a treeview in this datagrid and when I Click on a row I create an expand with "childs" ... So i would like to keep hierarchy after a sort ... Thats why I'm trying to find an issue with LINQ .. When I sort one column I have to keep the Hierarchy between parent and some "child rows" – user3190730 Jan 14 '14 at 08:47

1 Answers1

0

Finally I found a solution simply by ...

var query = myDataTable.AsEnumerable()
  .OrderByDesending( x => x.Field<type>("columnName"))
  .GroupBy( x => x.Field<type>'columnName").Substring(0,lenght)
  .SelectMany(x => x).CopyToDataTable();

  DataView.Table = query;
  DataView.Table.AcceptChange();

I'm not sure of my last SelectMany(x => x) but it's seems to work