Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
2.33/5 (2 votes)
See more:
I have this List below.



C#
class Program
{
    static void Main()
    {
    List<int> list = new List<int>();
    list.Add(1);
    list.Add(2);
    list.Add(3);
    list.Add(4);
    list.Add(5);

    // Remove all except first 3
   
    foreach (int i in list)
    {
        Console.Write(i);
    }

    }
}



How do I implement the code for it? Help needed.

Thanks in advance.
Posted

You can use Linq (take) to get the top 3 elements from the list:

http://msdn.microsoft.com/fr-fr/library/bb503062(v=vs.110).aspx[^]

C#
var firstThree = list.Take(3);
 
Share this answer
 
Comments
Sanket Saxena 14-Apr-14 5:34am    
Manas this is through LINQ.
Manas Bhardwaj 14-Apr-14 5:40am    
Yes, it is.

Why not use Linq?
Sanket Saxena 14-Apr-14 5:43am    
We can use but he ddin't mentioned in the question anything. Seems like a simple select/remove functionailty. Not saying anything to your solution.
Manas Bhardwaj 14-Apr-14 5:45am    
The question title is 'How do I select top items in list'?

Isn't it? And Linq is the simplest way to do it.
Sanket Saxena 14-Apr-14 5:47am    
exactly...hope the guy knows he is using LINQ.. :)
Try this:
C#
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);

 int remove = Math.Max(0, list.Count - 3);
     list.RemoveRange(3,remove);

     foreach (int i in list)
      {
         Console.Write(i);
      }
 
Share this answer
 
v4
Comments
Alif Marz 14-Apr-14 4:12am    
Hi, by using your code, I am getting a null list instead of the first 3 in that list.

Am I missing something?
Sanket Saxena 14-Apr-14 5:23am    
Solution updated try now
Manas Bhardwaj 14-Apr-14 5:47am    
+5. This would work.

See my answer for another approach.
Alif Marz 15-Apr-14 0:18am    
Thank you. Your solution worked.
Sanket Saxena 15-Apr-14 5:18am    
Always Welcome Alif...you can accept my solution

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900