There is a global news list.

List<NewsItem> allNews = new List<NewsItem>(); 

I need to take all these news, sort by date, without touching the global list, and display some range, which I do.

  var sortedNews = sortedByDate ? allNews.OrderBy(x => x.CreationDate).ToList() : allNews.OrderByDescending(x => x.CreationDate).ToList(); var articleRange = sortedNews.GetRange(firstIndex, itemsCount); 

copy operation + sorting takes up too much memory. Is it possible to somehow reduce the size of the resources used?

  • where do firstIndex and itemsCount ? - Igor
  • @Igor firstIndex is the number from which the selection of items begins, and itemsCount is the number of items to select. - Ashen One
  • Did I ask that? How are the values ​​of these variables determined? - Igor
  • @Igor static public HomePageModel GetHomePage(int page, bool sortedByDate) { int newsItemsQuantity = 15; var newsItemList = Storage.GetItems(page * newsItemsQuantity, newsItemsQuantity, sortedByDate); static public HomePageModel GetHomePage(int page, bool sortedByDate) { int newsItemsQuantity = 15; var newsItemList = Storage.GetItems(page * newsItemsQuantity, newsItemsQuantity, sortedByDate); - Ashen One

3 answers 3

Resources are allocated at the time of the call ToList , respectively, need to remove unnecessary calls.

The code can be made more beautiful

 var articleRange = allNews .OrderBy(x => x.CreationDate, !sortedByDate) .Skip(firstIndex-1) .Take(itemsCount) .ToList(); 

To do this, add your extension method.

 public static class LinqExtensions { public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, bool isDesc = false ) { return isDesc ? source.OrderByDescending(keySelector) : source.OrderBy(keySelector); } } 

    Use Skip and Take :

      var sortedNews = (sortedByDate ? allNews.OrderBy(x => x.CreationDate) : allNews.OrderByDescending(x => x.CreationDate)) .Skip(firstIndex-1).Take(itemsCount).ToList(); 

      So you take and create another copy of your data. Therefore you consume twice as much memory. Do without .ToList (), so you will only have an IEnumerable, then work with it. Cycle through it and add the necessary entries to articleRange. https://msdn.microsoft.com/ru-ru/library/bb534966 (v=vs.110).aspx

      Or try to use LINQ https://metanit.com/sharp/tutorial/15.3.php