-1

I have this list List<string> Url = new List<string>(); with more element >10 and i need to get only 5 element.

I tried in this mode i get all element:

foreach (string key3 in Url)
            {
                listBox3.Items.Add(key3);
            }
Federal09
  • 639
  • 4
  • 9
  • 25

6 Answers6

6
IEnumerable<string> firstFiveUrls = Url.Take(5);

Enumerable.Take documentation

So you could do:

// ObjectCollection.AddRange expects an array 
listBox3.Items.AddRange(Url.Take(5).ToArray()); 

ObjectCollection.AddRange documentation

Jamiec
  • 133,658
  • 13
  • 134
  • 193
3
for (int i = 0; i < 5; i++)
{
    listBox3.Items.Add(Url[i]);
}

If you can ensure that there are always > 5 elements, this should be ok.

MS_SP
  • 218
  • 2
  • 9
  • It is worth noting that with this approach you should validate the input to ensure it has at least 5 elements before looping – musefan Aug 14 '13 at 09:26
1

try this:

for(int i=0; i<5; ++i)
{
  listBox3.Items.Add(Url[i]);
}
Davide Piras
  • 43,984
  • 10
  • 98
  • 147
1

You can use GetRange

Url.GetRange(0,5);

listBox3.Items.AddRange(Url.GetRange(0,5));
Sayse
  • 42,633
  • 14
  • 77
  • 146
0

With Start index and count..

List<string> fiveURLs = URL.GetRange(0, 5);
Naren
  • 2,231
  • 1
  • 25
  • 45
0

first five elements

for (int i = 0; i < Url.Count && i < 5; i++)
    {
         listBox3.Items.Add(Url[i]);
    }

fifth element

listBox3.Items.Add(Url[4]);
Bronek
  • 10,722
  • 2
  • 45
  • 46