gpt4 book ai didi

c# - 使用 IEnumerable 时针对单个报告

转载 作者:太空宇宙 更新时间:2023-11-03 21:53:22 26 4
gpt4 key购买 nike

我有以下代码。所有 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;
}
}

最佳答案

 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();

顺便说一句 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 时的选择

关于c# - 使用 IEnumerable 时针对单个报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13425863/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com