Home > Net >  How can I convert a foreach loop to a LINQ statement?
How can I convert a foreach loop to a LINQ statement?

Time:01-04

foreach (var item in pList)
{
    if (item.PDate> Calendar.GetAppDate() && dtoPP.pLastDate < item.pLastDate)
    {
        dtoPP= item;
    }
}

i try to do that way, but where can i do assingment ( dtoPP= item;) that part?

pList.Where(item => item.PDate> Calendar.GetAppDate() && dtoPP.pLastDate < item.pLastDate ).ToList();

CodePudding user response:

To find the last item with a PDate greater than Calendar.GetAppDate() you can use the following query (assuming PDate and pLastDate are DateTime, or other comparable types):

var appDate = Calendar.GetAppDate();
var latestItem = pList
    .Where(i => i.PDate > appDate) // filter out any items where PDate <= appDate
    .OrderBy(i => i.pLastDate) // sort by pLastDate ascending (oldest to newest)
    .LastOrDefault(); // get the last item or default (null for reference types)

Note that I am caching the result of Calendar.GetAppDate(); so as to avoid evaluating it repeatedly as we go through pList.

CodePudding user response:

Here are two ways that could work. (UNTESTED)

var result = pList.FirstOrDefault(item => item.PDate > Calendar.GetAppDate() && dtoPP.pLastDate < item.pLastDate);
var result = pList.Where(item => item.PDate > Calendar.GetAppDate() && dtoPP.pLastDate < item.pLastDate).FirstOrDefault();

CodePudding user response:

You can use the LINQ Max method to find the element in pList with the maximum value of pLastDate, where PDate is greater than Calendar.GetAppDate():

dtoPP = pList.Where(i => i.PDate > Calendar.GetAppDate())
             .Max(i => i.pLastDate);
  • Related