3

Is it possible to pass the parameter after the period on a LINQ Query?

For example on this code:

objResultFinal = objResultFinal.OrderByDescending(x => x.[iwanttopassparameterhere]).ToList();

Is that possible? I want to declare after the "x." the string that I want to query.

Willy David Jr
  • 8,604
  • 6
  • 46
  • 57

4 Answers4

1
objResultFinal.OrderByDescending(s => s.GetType().GetProperty("PropertyName").GetValue(s, null));
Fabjan
  • 13,506
  • 4
  • 25
  • 52
Radim Drtílek
  • 256
  • 2
  • 7
1

Maybe this can be done using dynamic LINQ as below -

objResultFinal.OrderBy(passYourParameterHere).ToList();
R Jain
  • 486
  • 3
  • 9
0

Your list is that of type object? You'd either have to cast it first or use reflection.

Using casting:

var sortedList = objectList.Cast<Email>().OrderByDescending(item => item.EmailAddress).ToList();
ThePerplexedOne
  • 2,920
  • 15
  • 30
0
var list = new List<MyClass>();

list.Add(new MyClass { Name = "V" });
list.Add(new MyClass { Name = "B" });
list.Add(new MyClass { Name = "A" });
list.Add(new MyClass { Name = "C" });

//Create expression here, IF YOU ARE SORTING ON STRING PROPERTY KEEP KEY AS STRING OR CHANGE TO RESPECTIVE DATA TYPE
Func<MyClass,string> expression = s=>s.Name;

var ordered = list.OrderByDescending(expression).ToList();

The Class Object

class MyClass
{
    public string Name { get; set; }
}
Eldho
  • 7,795
  • 5
  • 40
  • 77