dimanche 1 novembre 2015

Using yield in a while loop to return one or many objects

I have two database methods. One fetches one row based on a name and creates an object out of it. The other is almost identical, but it fetches all rows and creates n objects out of it. I was hoping to use yield return to share the method that process the SQLLite data, but the issue I have is in CreateFooFromSQLSelect is telling me The body of CreateFooFromSQLSelect cannot be an iterator block becauseFoois not an iterator type. I really wasn't expecting that.

public Foo GetFoo(string name){
   string sql = "SELECT age FROM people WHERE name = " + name;
   return CreateFooFromSelect(sql);
}

public List<Foo> GetFoos(){
   List<Foo> foos = new List<Foo>();
   string sql = "SELECT * FROM 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"]);
   }
}

Aucun commentaire:

Enregistrer un commentaire