0

From my previous question. C# Linq OrderBy(x => x.property)

I specified my linq orderby argument dynamically.

var param = “attribute1”;    
var propertyInfo = typeof(data).GetProperty(param);    
List<data> newList = _list
  .OrderBy(x => propertyInfo.GetValue(x, null))
  .ToList();

the problem is when I want to order this by StringComparison.OrdinalIgnoreCase:

List<data> newList = _list
  .OrderBy(x => propertyInfo.GetValue(x, null), StringComparer.OrdinalIgnoreCase)
  .ToList();

I receive this error:

The type arguments for method 'System.Linq.Enumerable.OrderBy(System.Collections.Generic.IEnumerable, System.Func, System.Collections.Generic.IComparer)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

By not making it dynamic works. But I want this to order the dynamic argument.

List<data> newList = _list
  .OrderBy(x => x.Attribute, StringComparer.OrdinalIgnoreCase)
  .ToList();
Rand Random
  • 7,300
  • 10
  • 40
  • 88
Skyx
  • 103
  • 12

3 Answers3

4

Since propertyInfo.GetValue returns Object (not String) you have a syntax error. Try casting to String:

List<data> newList = _list
  .OrderBy(x => propertyInfo.GetValue(x, null) as String,
           StringComparer.OrdinalIgnoreCase)
  .ToList();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

Call ToString() on the result of GetValue():

List<data> newList = _list
  .OrderBy(x => propertyInfo.GetValue(x, null).ToString(), StringComparer.OrdinalIgnoreCase)
  .ToList();
adjan
  • 13,371
  • 2
  • 31
  • 48
  • 3
    Has the advantage that it "works " also for other types like `int`. But then you always have lexicographical order. `10` < `2`. Throws an exception if the property returns `null`. – Tim Schmelter May 04 '18 at 13:53
0

As GetValue method has object as return type. so we need to typecast it to String and will resolve your issue.

  newList.OrderBy(x => (string)propertyInfo.GetValue(x, null), StringComparer.OrdinalIgnoreCase).ToList();

try it out. hope it will work.

Suhail
  • 71
  • 4