1

I have a object Ob with several fields f1,..,fn (of different types). Now a list of object is shown in a GridView and I need to implement the sorting method.

The real problem is: how can I run

(from ob in Ob_list orderby ob.f1 ascending)

when the sorting field is represented by a string (i.e. "f1")? Unfortunately I am not able to get it with the reflection (I am not able to do something like ob.GetType().GetField("f1"), this is not mapped into sql code).

I have several fields to possibly sort the rows, which is the best&fastest approach to this?

Thank you very much!

Jace Rhea
  • 4,982
  • 4
  • 36
  • 55
Desmond
  • 567
  • 1
  • 7
  • 17

2 Answers2

0

LINQ execution is deferred until you actually enumerate over the results or access the "count", etc. Because of this, you can build up your LINQ statement in stages.

The below code is done in C#, but I'm sure the equivalent is possible in VB.NET.

First setup your basic query:

var query = (from ob in Ob_list);

At this point, nothing has actually gone to the database due to deferred execution.

Next, conditionally add your order by components:

if (sortField == "f1")
{
  query = query.OrderBy(o => o.f1);
}
else if (sortField == "f2")
{
  query = query.OrderBy(o => o.f2);
}
else 
{
  //...
}

And finally, collect your results

foreach (var item in query)
{
  // Process the item
}
Matt Houser
  • 33,983
  • 6
  • 70
  • 88
  • fine, but the main issue is the number of sorting key (now 10, possibly up to 25), and for each of them I should also consider ASC or DESC. this means 50 choices in the worst case, that's why I would like to do something "magic" dinamically or using reflection. – Desmond Jul 18 '13 at 06:59
0

I've found this question: How do I specify the Linq OrderBy argument dynamically?

I'm using Entity Framework, so the first answer did not solved my problem. The second one however, worked great!

Hope it helps!

Community
  • 1
  • 1
drigomed
  • 186
  • 2
  • 9