Home > Mobile >  filtering cumbersome list of objects with linq
filtering cumbersome list of objects with linq

Time:12-01

I have a cumbersome list of objects. The count is about 25.837. once I want to filter my object with such this linq expression

        underManagementPersonList.OrderByDescending(x => x.BarCode).Where(x => x.CardNum.Contains("0480286000") || x.BarCode.Contains("0480286000") || x.PersonName.Contains("0480286000")).Skip(pageIndex).ToList();   Evaluation timed out    System.Collections.Generic.List<GTS.Clock.Model.MonthlyReport.UnderManagementPerson>

I get this error

Evaluation timed out

ALthogh there is no such problem with fewer items like below which jusk I get 100 items

underManagementPersonList.Take(100).OrderByDescending(x => x.BarCode).Where(x => x.CardNum.Contains("0480286000") || x.BarCode.Contains("0480286000") || x.PersonName.Contains("0480286000")).Skip(pageIndex).ToList();

enter image description here

CodePudding user response:

Because this is simply a list of objects then the order is important - you can speed things up by placing your .Where() before your .OrderByDescending()

underManagementPersonList
    .Where(x => x.CardNum.Contains("0480286000")
        || x.BarCode.Contains("0480286000")
        || x.PersonName.Contains("0480286000"))
    .OrderByDescending(x => x.BarCode)
    .Skip(pageIndex)
    .ToList();

This still has the potentially expensive/slow string.Contains calls on as many as 3 times on 25,837 objects but at least you'll only be sorting the subset of objects which match your Where.

NOTE: Placing the Where before the OrderByDescending will produce the same set of objects in the same order - the difference is that as long as at least one of the objects is filtered out by your where then it will be faster - the smaller the set that matches your where the faster the orderby will be.

  • Related