简体   繁体   中英

How can I convert a foreach loop to a LINQ statement?

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();

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 .

Here are two ways that could work. (UNTESTED)

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

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);

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