gpt4 book ai didi

c# - 后面的ienumerable trought代码如何实现?

转载 作者:太空宇宙 更新时间:2023-11-03 16:59:51 24 4
gpt4 key购买 nike

我想在我的代码中实现 ienumerable 以便它是只读的,但我不知道在哪里可以实现它。到目前为止,我还没有在互联网上找到任何可以解决我的问题的解决方案。截至目前,我只使用过 List 并想将 ienumerable 集成到我的代码中。此外,如果您发现不良的编码做法,请随时提出任何建议。

我试过了

public static List<GuitarItems> GetGuitarItems(string itemCategory)
{
List<GuitarItems> list = new List<GuitarItems>();
string query = string.Format("SELECT * FROM guitarItems WHERE brand LIKE @brand");

try
{
conn1.Open();
command1.CommandText = query;
command1.Parameters.Add(new SqlParameter("brand", itemCategory));
SqlDataReader reader = command1.ExecuteReader();

while (reader.Read())
{
int id = reader.GetInt32(0);
string type = reader.GetString(1);
string brand = reader.GetString(2);
string model = reader.GetString(3);
double price = reader.GetDouble(4);
string itemimage1 = reader.GetString(5);
string itemimage2 = reader.GetString(6);
string description = reader.GetString(7);
string necktype = reader.GetString(8);
string body = reader.GetString(9);
string fretboard = reader.GetString(10);
string fret = reader.GetString(11);
string bridge = reader.GetString(12);
string neckpickup = reader.GetString(13);
string bridgepickup = reader.GetString(14);
string hardwarecolor = reader.GetString(15);

GuitarItems gItems = new GuitarItems(id, type, brand, model, price, itemimage1, itemimage2, description, necktype, body,
fretboard, fret, bridge, neckpickup, bridgepickup, hardwarecolor);
list.Add(gItems);
}
}
finally
{
conn1.Close();
command1.Parameters.Clear();
}

return list;
}

private void FillPage()
{
List<GuitarItems> itemList = new List<GuitarItems>();
List<string> itemListPage = new List<string>();

itemList = ConnectionClassGuitarItems.GetGuitarItems(brandType);

StringBuilder sb = new StringBuilder();

foreach (GuitarItems gList in itemList)
{
itemListPage.Add("GuitarItemsIbanezDetails" + (x + 1) + ".aspx");

sb.Append(
string.Format(
@"
<div class='one-two'>
<a href='{3}' runat="'server'"><img runat="'server'" src='{0}'/></a>
<div class='content'>
<div id='label'>{1} {2}</div>
</div>

</div>", gList.ItemImage1, gList.Brand, gList.Model, itemListPage[x]));

x++;

}

最佳答案

尝试使用迭代器方法:

public static IEnumerable<GuitarItems> GetGuitarItems(string itemCategory)
{
using (var con = new SqlConnection("..."))
using (var cmd = new SqlCommand("SELECT * FROM guitarItems WHERE brand LIKE @brand", con))
{
cmd.Parameters.AddWithValue("@brand", itemCategory);`

con.Open();
using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
while (reader.Read())
{
int id = reader.GetInt32(0);
...

yield return new GuitarItems(id, ...);
}
}
}
}

关于c# - 后面的ienumerable trought代码如何实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44308201/

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