gpt4 book ai didi

c# - foreach循环问题

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

有没有其他更短/更有效的方法来检查它是否是我的列表框中的最后一项?这里的主要目标基本上是将选定的项目添加到标签中,并在除最后一个之外的每个项目之后添加一个逗号。有什么建议吗?

        int sc = 0;
List<string> interestitems = new List<string>();

foreach (ListItem siitem in ListBox1.Items)
{
if (siitem.Selected == true)
{
interestitems.Add(siitem.Value.ToString());
}
}

foreach (string inteitem in interestitems)
{
Label1.Text += inteitem;
sc++;
if (sc < interestitems.Count)
{
Label1.Text += ",";
}
}

最佳答案

不要使用第二个循环:

Label1.Text = string.Join("," , interestitems);

附言

如果您使用的是 .net 3.5,则需要将字符串数组传递给 string.Join(),然后:

Label1.Text = string.Join("," , interestitems.ToArray());

编辑:

如果你想完全避免循环就这样做:

var selItems = ListBox1.Items.Cast<ListItem>()
.Where(item => item.Selected)
.Select(item => item.ToString());

Label1.Text = string.Join("," , selItems);

关于c# - foreach循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5170768/

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