开发者

Change the order by field based on a condition

开发者 https://www.devze.com 2023-03-06 19:39 出处:网络
I have a scenario where I have t开发者_如何学Co change the order by field based on some condition.

I have a scenario where I have t开发者_如何学Co change the order by field based on some condition.

from summaryRows in _summaryTable.AsEnumerable()
where summaryRows.Field<string>("AirlineDisplayName")
                 .Equals(airlineName_, StringComparison.OrdinalIgnoreCase) 
orderby summaryRows.Field<decimal>("FareAdult")
select new
{
    summaryTableRow = summaryRows
};

Based on the condition, I have to change the order by field to orderby summaryRows.Field<double>("BasePricePlusTaxAndFees") Here, both the field data type is different. How can I do it in one query?


I think this will be the most readable using fluent Linq syntax and introducing an if-statement while building the query.. Since you do not explain your condition, I assume that you have a boolean variable called condition with the appropriate value:

var query = _summaryTable.AsEnumerable()
     .Where(
         summaryRows => summaryRows.Field<string>("AirlineDisplayName")
             .Equals(airlineName_, StringComparison.OrdinalIgnoreCase));

if (condition)
    query = query.OrderBy(summaryRows => summaryRows.Field<decimal>("FareAdult"));
else
    query = query.OrderBy(summaryRows => summaryRows.Field<double>("BasePricePlusTaxAndFees"));

var resultQuery = query.Select(summaryRows => new
    {
        summaryTableRow = summaryRows
    });

Disclaimer: I have not tested it, but good luck.


What about this:

orderby conditionIsTrue ? (IComparable)summaryRows.Field<double>("BasePricePlusTaxAndFees") : (IComparable)summaryRows.Field<decimal>("FareAdult")
0

精彩评论

暂无评论...
验证码 换一张
取 消