簡體   English   中英

C#Linq查詢以選擇滿足條件的最佳結果

[英]C# Linq query to select top result where a condition is satisfied

請原諒我的英語,但我會解釋我要達到的目標。 標題可能含糊不清。

我正在開發一個薪資程序,需要查詢月度表以選擇要使用linq處理的月份。 它用於SAP Business 1附加組件。

我的月度表(縮短)

Code    U_Month    U_Pay_Process_Status
1       Jan        Y
2       Feb        Y
3       March      Y
4       April      N
5       May        N
6       June       N
7       July       N
8       Aug        N
9       Sept       N
10      Oct        N
11      Nov        N
12      Dec        N

一旦處理了工資單月,例如一月,該月的U_Pay_Process_Status字段將更改為Y(是)

對於上表,我將如何在SQL查詢中編寫linq以選擇第一個未處理的月份(在本例中為April)?

我到目前為止

代碼是SAP中自動生成的主鍵,類型為varchar。

// Get service instance needed
var monthlyPeriodService = Program.Kernel.Get<IMonthlyPeriodService>();

//Query database monthly periods
var monthlyPeriods = monthlyPeriodService.GetAllMonthlyPeriods().OrderBy(m => m.Code);

To do.......

我如何獲得第一個未處理的月份。 任何幫助表示贊賞。

怎么樣:

var firstUnprocessed = monthlyPeriodService.GetAllMonthlyPeriods()
                                           .Where(m => !m.Processed)
                                           .OrderBy(m => m.Code)
                                           .FirstOrDefault();

請注意,如果所有期間都已處理(這就是OrDefault位為您執行的操作),它將返回null。

或者:

var firstUnprocessed = monthlyPeriodService.GetAllMonthlyPeriods()
                                           .OrderBy(m => m.Code)
                                           .FirstOrDefault(m => !m.Processed);

前一個版本訂購結果之前會過濾掉已處理的項目。 如果查詢是在過程中執行的,這將使其效率更高(盡管效率是否顯着 )。 如果這使用的是LINQ提供程序,該提供程序會將查詢轉換為SQL或類似的內容,那就沒關系了。

嘗試使用以下方法

monthlyPeriods.FirstOrDefault()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM