【问题标题】:Switch Case for dynamic amount of valuesSwitch Case 用于动态数量的值
【发布时间】:2016-11-01 00:46:38
【问题描述】:

这是我的Program

您可以在此网格视图中添加任意数量的行,当您按下“就绪”按钮时,程序会通过 KeyDown-Event 监视您的输入。 当您按下网格视图中显示的热键之一时,您将获得匹配路径中的所有歌曲。

我想我可以这样做:

switch (e.KeyValue.ToString().Substring(0, 0))    
{
    foreach (DataGridViewRow  item in grdView)
    {
        case item.Cells[2].Value:
        //Get all the songs
        break;
    }        
}

不幸的是,我遇到了很多错误。我想它不会像这样工作。 有没有其他方法可以要求所有写在 gridview 中的热键?

感谢您的任何建议。

【问题讨论】:

  • 请先研究switch syntax,您可以在switch之外或switch - case内放置一个for each循环,但不要像这样重叠它们

标签: c# gridview foreach switch-statement case


【解决方案1】:
foreach (DataGridViewRow item in grdView)
{
    if(item.Cells[2].Value == theValueYouAreLookingFor)
    {
        // Do something here
        break;
    }
}

而且 e.KeyValue.ToString().Substring(0, 0) 看起来也不正确,我很确定它不会完全按照你的意愿去做。

【讨论】:

  • 哦,该死的,这很容易。非常感谢! :)
【解决方案2】:

虽然使用 foreach 遍历所有项目并检查是否相等会起作用,

我认为值得一提的是,以防将来有人找到它:

一个是Linq:

var itemFound = grdView.FirstOrDefault(item => item.Cells[2].Value == theValueYouAreLookingFor);
if (itemFound == null)
{
    //no items found in this case
}

另一个是Dictionary,它通常是映射动态选项数量的更有效解决方案,但您必须事先构建它:

简单的构建示例(在创建/更改网格时执行此操作):

shortcutsMap = grdView.ToDictionary(item => item.Cells[2].Value, item);

得到:

var itemFound = shortcutsMap[theValueYouAreLookingFor] //will throw exception if not found

或:

shortcutsMap.TryGetValue(theValueYouAreLookingFor, out var itemFound) //returns true/false if found and result will be at itemFound

【讨论】:

    猜你喜欢
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 2021-01-29
    相关资源
    最近更新 更多