从For循环返回值

Bal*_*i C 1 c# for-loop return winforms

我的应用程序中有listView.我遍历项目以检查当前选择的项目,然后返回一个值.由于所有路径都必须返回一个值,我必须返回一个覆盖for循环返回的循环外的值,如何在循环之后保留它而不覆盖它?

public string GetItemValue()
{
    for (int i = 0; i < listView1.Items.Count; i++)
    {
        if (listView1.Items[i].Checked == true)
        {
            return listView1.Items[i].Text; // I want to keep this value
        }
     }
     // Without overwriting it with this but the compiler 
     // requires me to return a value here
     return "Error"; 
}
Run Code Online (Sandbox Code Playgroud)

任何帮助都非常感谢.谢谢.

PS我尝试过使用if但是没有运气.

Bis*_*ook 9

编辑时:从上面删除我的评论.

你不必担心这个.一旦它击中return循环内的第一个,它将立即返回该值.在这种情况下,循环外没有代码.

顺便说一句,这段代码会更干净:

public string GetItemValue()
{
    foreach (var item in listView1.Items)
    {
        if (item.Checked) return item.Text;
    }
    throw new InvalidOperationException("No checked items found");
}
Run Code Online (Sandbox Code Playgroud)

例外的是处理错误的更地道的方式,以及foreach循环最好一个for循环,当你只是遍历集合.

使用LINQ,您可以更简洁:

public string GetItemValue()
{
    return listView1.Items.Cast<ListViewItem>().Single(i => i.Checked).Text;
}
Run Code Online (Sandbox Code Playgroud)