在下面的代碼:如何有條件地使用lambda和非lambda linq?
var results = from service
in LogisticsService.GetTransportationModes<CarrierTransportationMode>
(
x => x.CarrierId == carrierRoleId &&
x.ParentTransportationModeId != null &&
!(x is LoadCarrierMode) &&
(x.ParentTransportationMode.TransportationModeStatus != null) &&
x.ParentTransportationMode.TransportationModeStatus.Value != TransportationModeStatus.Inactive
)
//.OrderByDescending(o => o.IsDefault)
//.ThenBy(t => t.ParentTransportationMode.Name)
orderby service.IsDefault descending, service.ParentTransportationMode.Name
select new
{
text = service.ParentTransportationMode.Name,
value = service.ParentTransportationMode.Id
};
如果service.IsDefault
是空的,我需要跳過的OrderBy/thenby完全。這樣,如果有存在於LINQ沒有排序依據如下面的代碼將執行:
var results = from service
in LogisticsService.GetTransportationModes<CarrierTransportationMode>
(
x => x.CarrierId == carrierRoleId &&
x.ParentTransportationModeId != null &&
!(x is LoadCarrierMode) &&
(x.ParentTransportationMode.TransportationModeStatus != null) &&
x.ParentTransportationMode.TransportationModeStatus.Value != TransportationModeStatus.Inactive
)
select new
{
text = service.ParentTransportationMode.Name,
value = service.ParentTransportationMode.Id
};
我試圖修改查詢的條件象下面這樣:
.OrderByDescending(o => o.IsDefault.HasValue ? o.IsDefault : null)
.ThenBy(t => t.IsDefault.HasValue ? t.ParentTransportationMode.Name : null)
orderby !service.IsDefault.HasValue ? null: service.IsDefault descending, service.ParentTransportationMode.Name
但是這並沒有幫助。
我是否需要傳遞orderby中的任何特殊參數,以便排序永遠不會有條件地發生?任何關鍵字如'case'左右都可以使用?如果是這樣,怎麼樣?
將不勝感激任何幫助! 謝謝!
您是否希望所有具有'service.IsDefault == null'的元素在具有'service.IsDefault == null'的所有元素之前或之後? –
那麼,如果service.IsDefault == null,我希望所有元素都是從數據庫中獲取的順序。只有當任何元素具有service.IsDefault == true時,我們才應該考慮排序,而不是其他情況。 – zapper