c# - Using yield in a while loop to return one or many objects -
i have 2 database methods. 1 fetches 1 row based on name , creates object out of it. other identical, fetches rows , creates n
objects out of it. hoping use yield return
share method process sqllite data, issue have in createfoofromsqlselect
telling me the body of createfoofromsqlselect cannot iterator block because
foois not iterator type
. wasn't expecting that.
public foo getfoo(string name){ string sql = "select age people name = " + name; return createfoofromselect(sql); } public list<foo> getfoos(){ list<foo> foos = new list<foo>(); string sql = "select * people"; foos.add(createfoofromselect(sql)); } private foo createfoofromselect(string sql){ foo foo; sqlitecommand command = new sqlitecommand(sql, sqlconnection); sqlitedatareader reader = command.executereader(); while(reader.read()){ yield return foo = new foo(reader["age"]); } }
you can use yield
statement on methods return ienumerable<t>
. in case method returns foo
, cannot use yield
statement there. instead can try such approach:
private ienumerable<foo> createfoofromselect(string sql){ sqlitecommand command = new sqlitecommand(sql, sqlconnection); sqlitedatareader reader = command.executereader(); while(reader.read()){ yield return new foo(reader["age"]); } }
in case instead of using add
can use addrange
:
public list<foo> getfoos(){ list<foo> foos = new list<foo>(); string sql = "select * people"; foos.addrange(createfoofromselect(sql)); }
you can read more yield
keyword on msdn
Comments
Post a Comment