8

how can I get the top 30 items in a list in C# and add it to a new list?

I have a list of about a 1000 items, and want to create new lists, of about 30 items each, and then somehow bind the lists to listbox

Bohrend
  • 1,467
  • 3
  • 17
  • 26

5 Answers5

21

Use LINQ Take() method:

var top30list = source.Take(30).ToList();

Add using System.Linq at the top of your file to make it work.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
6

everybody is saying linq so i'll show example without linq:

List<object> newList = new List<object>();

for(int i=0 ; i < 30 ; i++)
    newList.Add(oldList[i]);
No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
5

Use Take(30)

public List<string> ReturnList(List<string> mylist,int page)
{
    return mylist.Skip(30 * (page - 1)).Take(30)
}
Giannis Paraskevopoulos
  • 18,261
  • 1
  • 49
  • 69
  • 1
    Useful as is implied requirement is to get the top 30, followed by the next 30, etc. In that scenario the list.Skip() is required information. – Morvael Oct 31 '17 at 12:03
4
newList.AddRange(list.Take(30));
Rex
  • 2,130
  • 11
  • 12
2

use orderbywith column name after that use as .Take(30) will select the 30 items from the list.

Amit
  • 15,217
  • 8
  • 46
  • 68