I have the following code.
All 20 objects seem to get created ok.
The first foreach then works fine and iterates through all 20.
The second example using linq works well aswell.
Is it then possible to target just one of the objects, using a property such as ReportKey, and run the method RunThisReport just for that object? Or, because I’ve used the type IEnumerable<> have I gone down a dead-end?
static void Main(string[] args) {
var models = SelectReports("SELECT * FROM 20RecordTable");
//1.running the method for each
foreach(myReport x in models) {
Console.WriteLine("Doubled key:{0}", x.myReportKeyDoubled().ToString());
}
//2.linq sample
var result = from sample in models
select sample.ReportName;
foreach(string x in result) {
Console.WriteLine(Convert.ToString(x));
}
//3. target a single report say reportKey 512 and run the method RunThisReport?
Console.WriteLine("Press [enter] to exit");
Console.Read();
}
static IEnumerable<myReport> SelectReports(string myCommandText) {
var connectionString = ConfigurationManager.ConnectionStrings["xxx"].ConnectionString;
using(var conn = new SqlConnection(connectionString))
using(var cmd = conn.CreateCommand()) {
conn.Open();
cmd.CommandText = myCommandText;
using(var reader = cmd.ExecuteReader()) {
while(reader.Read()) {
yield return new myReport {
ReportKey = reader.GetInt32(reader.GetOrdinal("ReportKey")),
ReportName = reader.GetString(reader.GetOrdinal("ReportName")),
ReportDescription = reader.GetString(reader.GetOrdinal("ReportDescription")),
ReportTechDescription = reader.GetString(reader.GetOrdinal("ReportTechDescription "))
};
}
}
}
}
public class myReport {
public int ReportKey { get; set; }
public string ReportName { get; set; }
public string ReportDescription { get; set; }
public string ReportTechDescription { get; set; }
public int myReportKeyDoubled() {
return ReportKey*2;
}
public string RunThisReport(){
return this.ReportName + " needs to be run via" + this.ReportTechDescription;
}
}
Or with comprehension syntax (ugly, yes?):
BTW with Dapper your code will look like:
Dapper is available via NuGet. And it’s my choice when working with ADO.NET