C# IEnumerator/yield structure potentially bad?

前端 未结 11 1483
面向向阳花
面向向阳花 2021-02-01 02:47

Background: I\'ve got a bunch of strings that I\'m getting from a database, and I want to return them. Traditionally, it would be something like this:

public Li         


        
11条回答
  •  忘掉有多难
    2021-02-01 03:28

    You are not missing anything. Your sample shows how NOT to use yield return. Add the items to a list, close the connection, and return the list. Your method signature can still return IEnumerable.

    Edit: That said, Jon has a point (so surprised!): there are rare occasions where streaming is actually the best thing to do from a performance perspective. After all, if it's 100,000 (1,000,000? 10,000,000?) rows we're talking about here, you don't want to be loading that all into memory first.

提交回复
热议问题