简体   繁体   中英

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

Excuse my English but I will explain what I am trying to achieve. The title may be vague.

I am developing a Payroll program and needed to query a monthly table in order to select a month for which to process using linq. It is for a SAP Business 1 add-on.

My monthly table (shortened)

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

Once a payroll month has been processed, eg January, the U_Pay_Process_Status field for that month is changed to Y (Yes)

For the above table, how would I write a linq to sql query to select the first unprocessed month (in this case April)?

I have this so far

Code is an automatically generated Primary Key in SAP and it is of type 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.......

How do I get the first unprocessed month. Any help appreciated.

How about something like:

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

Note that this will return null if all periods have been processed (that's what the OrDefault bit does for you).

Alternatively:

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

The former version filters out the processed items before ordering the results; this will make it more efficient (although whether the efficiency is significant or not is another matter) if the query is performed in-process; if this is using a LINQ provider which is converting the query to SQL or something similar, it's unlikely to matter.

尝试使用以下方法

monthlyPeriods.FirstOrDefault()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM