2

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
  • 7,817
  • 5
  • 40
  • 51

4 Answers4

1
objResultFinal.OrderByDescending(s => s.GetType().GetProperty("PropertyName").GetValue(s, null));
Fabjan
  • 13,050
  • 3
  • 22
  • 49
Radim Drtílek
  • 246
  • 2
  • 7
1

Maybe this can be done using dynamic LINQ as below -

objResultFinal.OrderBy(passYourParameterHere).ToList();
R Jain
  • 416
  • 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,860
  • 13
  • 29
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,344
  • 3
  • 41
  • 72