Amending code to make it list some files in a directory, rather than all The method list_all() is the code I am starting with. It just lists all files in "c:\windows".

I want to adjust it to list only the first 10 files (if there are as many files as that there).

I can see that Directory.GetFiles(sDir) returns an array of string.  The original method list_all(), takes all of them.  I want mine to just take the first 10, or if there's less than 10 then all of them.  But i've added four lines of code and used a list, to do it. My amended method is list_some()

It's far from a disaster, but I'm sure there's a better way though I'm not sure.

using System;
using System.Collections.Generic;
using System.IO;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {

            static void list_all()
            {
                string sDir = "c:\\windows";

                foreach (string f in Directory.GetFiles(sDir))
                {
                     Console.WriteLine(f);
                }

            }

            static void list_some()
            {
                string sDir="c:\\windows";

                List&lt;string&gt; lstsomefiles = new List&lt;string&gt;();
                int count = Directory.GetFiles(sDir).Length;
                string[] strs_fileslst = Directory.GetFiles(sDir);

                for (int i = 0; i &lt; count &amp;&amp; i &lt; 10; i++) lstsomefiles.Add(strs_fileslst[i]);

                foreach (string f in lstsomefiles)
                {

                    Console.WriteLine(f);
                }

            }

        }
    }
}
You can utilize the .Take() method in LINQ which:


  Returns a specified number of contiguous elements from the start of a sequence


Using this, your code would look as follows:

string sDir = "c:\\windows";

foreach (string f in Directory.GetFiles(sDir).Take(10))
{
    Console.WriteLine(f);
}