简体   繁体   中英

Select object and add to list linq c#

probably a simple Q but still a beginner at this and not sure on how to.... Each WorkStation can have a number of Invoices So my below code will....

store all the workStations, go Through each workStation,
get the last (most recent) invoice for that workStation,
If the invoices date (for the most recent Invoice) is < 12 Months

Add it to the list of sites...

EDIT: Thanks for all the help guys but I am trying to do it through c# and avoid the LINQ searche you guys have mentioned...thanks for everyone who replied...

My new problem being i need to sort the ChosenInvoices list into asceding order and return the first...as i think it is selecting anyone in the list:

 var allWorkSites =
            (from worksites in db.Work_Sites
             select worksites).Distinct().ToList();
    List<Object> chosenInvoices = new List<Object>();

    foreach (Work_Site worksite in allWorksites)
    {
        Invoice lastInvoice = worksite.Invoices.LastOrDefault();

        if (lastInvoice != null)
        {
            if (lastInvoice.Invoice_Date < DateTime.Now.AddMonths(-12))
            {
                chosenInvoices.Add(workstation);
            }
        }
    }
List<invoice> actualInvoices = db.Work_Stations.Distinct()
        .Where(w => w.Invoices.Last().Invoice_Date < DateTime.Now.AddMonths(-12)).Select(w => w.Invoices.Last()).ToList();

This code will return you the list of most recent invoices from each workstation.

To sort your invoice in asscending order list have a method OrderBy() , so order it with this method and then take the first one.

Also list have Sort() method.

allWorkStations
    .Where(w => w.Invoices.Last().Invoice_Date < DateTime.Now.AddMonths(-12))
    .Select(w => list.add(w));

Or better yet:

List<Work_Station> list = db.Work_Stations
    .Distinct()
    .Where(w => w.Invoices.Last().Invoice_Date < DateTime.Now.AddMonths(-12))
    .ToList();
var allWorkStations =
            (from workstation in db.Work_Stations
             where workstation.Invoices.Last().Invoice_Date < DateTime.Now.AddMonths(-12)
             select workstation).Distinct();

The following code will create list of workstations which had invoice in last year

var checkDate = DateTime.Now.AddMonths(-12);

var resultList = db.Work_Stations
  .Distinct()
  .Select(ws => new {Ws = ws, Li = ws.Invoices.OrderBy(i => i.Invoice_Date).LastOrDefault()})
  .Where(item => item.Li != null && Li.Invoice_Date < checkDate)
  .Select(item => item.Ws)
  .ToList();

This will work even if the invoices are not in date order:

invoiceLst.AddRange(allWorkStations
    .Where(w => w.Invoices.Max(i => i.Invoice_Date) < DateTime.Now.AddMonths(-12)));

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