Question

I receive this parameter from my request:

sort=homeCountry

I need to sort by whatever column is sent to the sort parameter, so I created a method like so:

string sort = "homeCountry";
Func<PaymentRateTrip, string> orderBy = (
    x => sort == "homeCountry" ? x.HomeCountry :
        sort == "hostCountry" ? x.HostCountry :
            sort == "homeLocation" ? x.HomeLocation :
                sort == "hostLocation" ? x.HostLocation :
                    x.HomeLocation
);

This works correctly.

However, the columns above are all strings. But, I also need to add decimal columns like so:

string sort = "homeCountry";
Func<PaymentRateTrip, string> orderBy = (
    x => sort == "homeCountry" ? x.HomeCountry :
        sort == "hostCountry" ? x.HostCountry :
            sort == "homeLocation" ? x.HomeLocation :
                sort == "hostLocation" ? x.HostLocation :
                    sort == "oneWayRate" ? x.oneWayRate :
                    x.HomeLocation
);

It gives me an error on the x.HostLocation that says:

Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'decimal?'

Is there a better way to do what I am trying to do? I am looking for:

  • A way that will work.
  • A way that is readable (something like a switch case).

Edit: PaymentRateTrip.cs

public class PaymentRateTrip
{
    public Guid? Id { get; set; }
    public Guid HomeCountryId { get; set; }
    public string HomeCountry { get; set; }
    public Guid HomeLocationId { get; set; }
    public string HomeLocation { get; set; }
    public Guid? HostCountryId { get; set; }
    public string HostCountry { get; set; }
    public Guid? HostLocationId { get; set; }
    public string HostLocation { get; set; }
    public decimal? OneWayRate { get; set; }
    public decimal? RoundTripRate { get; set; }
    public Guid? OneWayCurrencyId { get; set; }
    public Guid? RoundTripCurrencyId { get; set; }       

}
Was it helpful?

Solution

I'd just make an extension method:

public static IEnumerable<PaymentRateTrip> Sort(this IEnumerable<PaymentRateTrip> list, string sort)
{
    switch (sort)
    {
        case "homeCountry":
            return list.OrderBy(x => x.Whatever);
        case "somethingElse":
            return list.OrderBy(x => x.Whatever);

        //....
    }
}

OTHER TIPS

It might seem to simple but just do this

        var prop = typeof(PaymentRateTrip).GetProperty(sort);
        var ordered = lst.OrderBy(p => prop.GetValue(p));

this works as long as the sort name is part of the object. In your case the function is (p => prop.GetValue(p))

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top