What are the benefits of using IEnumerable over an array?

After I asked my Code Review.stackexchange question , I was advised to use the following code snippets. And I noticed that during the transfer, the string [] Lines is set to IEnumerable.

After looking a bit at the IEnumerable function, I did not find anything that would suggest a performance improvement. So is it just for readability? Or is there a performance difference or a general advantage using IEnumerable instead of an array?

private void ProcessSingleItem(String fileName, String oldId, String newId)
{
    string[] lines = File.ReadAllLines(fileName);

    File.WriteAllText(fileName, ProcessLines(lines, oldId, newId));
}  

private String ProcessLines(IEnumerable<String> lines, String oldId, String newId)
{
    StringBuilder sb = new StringBuilder(2048);
    foreach (String line in lines)
    {
        sb.AppendLine(line.Replace(oldId, newId));
    }
    return sb.ToString();
}  
+4
source share
5 answers

An array is an implementation IEnumerable.

, lines , , IEnumerable. , IEnumerable , , IEnumerable .

:

ProcessLines(GetItems(), ...);

public IEnumerable<string> GetItems()
{
    yield return "ItemAlwaysGetsIncluded";

    if (!once_in_blue_moon)
    {
        yield break;
    }

    yield return "ItemIncludedOnceInABlueMoon";
}

, , IEnumerable .

+11

, , , . . .

  • Pro: , , , : " , ". , , , ?

  • Con: , . , ? . , . , : , , .. , .

  • . , , - . , , ; . A foreach for; IEnumerable , , . ? , . , , , , , . , ? , .

+13

. , .

, IEnumerable .

, . - , .

, IEnumerable - ,

+4

IEnumerable "" . , . - , IEnumerable n- - - , IEnumerable , .

Array (.. )

+2

, , IEnumerable ,

System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");

while((line = file.ReadLine()) != null)
{
   yield return line;
}

file.Close();

, , .

, , IEnumerable , IEnumerable, List any type.

+1

All Articles