我有以下代码。
似乎所有20个对象都被创建了
然后第一个foreach
正常工作并遍历所有20
使用linq
的第二个示例也很有效。
然后是否可以使用ReportKey
之类的属性仅定位其中一个对象,并为该对象运行方法RunThisReport
?或者,因为我使用了类型IEnumerable<>
,我走了一条死路?
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;
}
}
答案 0 :(得分:2)
var report = models.SingleOrDefault(m => m.ReportKey == 512);
if (report != null)
report.RunThisReport();
或者用理解语法(丑陋,是吗?):
var report = (from m in models
where m.ReportKey == 512
select m).SingleOrDefault();
BTW与Dapper您的代码将如下所示:
static IEnumerable<myReport> SelectReports(string myCommandText)
{
var connectionString = ConfigurationManager.ConnectionStrings["xxx"].ConnectionString;
using(var conn = new SqlConnection(connectionString))
{
conn.Open();
return conn.Query<myReport>(myCommandText);
}
}
Dapper可通过NuGet获得。在使用ADO.NET时,这是我的选择
答案 1 :(得分:1)
models.First(x => x.ReportKey == 42).RunThisReport();
答案 2 :(得分:1)
如果我正确地阅读此内容,那么您正在努力使用LINQ来获取对象。这里最简单的方法是使用LINQ扩展方法。我相信这就是你要找的东西:
models.First(i => i.ReportKey == yourReportKey).RunThisReport();
或者澄清这里发生了什么:
// Get the report that matches the key
myReport report = models.First(i => i.ReportKey == "YOUR-KEY-VALUE");
// Call RunThisReport for that report.
report.RunThisReport();
这也适用于收藏:
models.Where(i => i.ReportKey == yourReportKey).ForEach(report => report.RunThisReport());
希望有所帮助!如果没有,请澄清你的问题,我很乐意提供帮助。