【问题标题】:separating strings by some text within listbox用列表框中的一些文本分隔字符串
【发布时间】:2019-04-10 19:46:41
【问题描述】:

我有一个ListBox,其中表名是这样写的:

Staging_Section_01_2019_03_19_01  
Staging_Section_01_2019_03_20_01  
Staging_Section_23_2019_03_21_01  
Staging_Section_52_2019_03_23_01  
Staging_Section_52_2019_03_24_01  

我要做的是按节号将它们分开,所以我希望所有Section_01 都在一个List 对象中,Section_23 在另一个List 对象中,依此类推。动态的性质让我很难。

到目前为止,我有以下内容:

foreach (var it in uploadBox.Items)
{
    if (it.ToString().Contains("Section"))
    {
        section = it.ToString().Substring(0, 18);
        found = it.ToString().IndexOf("_");
        section = section.Substring(found + 1);
        sectionNum = section.Substring(8, 2);
    }
}

我得到了sectionNum,它只是数字和部分,就像Section_01 这样的字符串。

知道如何解决这个问题吗?

预期的输出是这样的:

列表 1

Staging_Section_01_2019_03_19_01  
Staging_Section_01_2019_03_20_01  

清单 2

Staging_Section_23_2019_03_21_01  

清单 3

Staging_Section_52_2019_03_23_01  
Staging_Section_52_2019_03_24_01  

【问题讨论】:

  • 这看起来非常适合正则表达式。
  • 我认为操作的问题是如何将它们按编号分开。
  • 请向我们展示您的预期输出示例
  • 还有,是否有可能有一个 Section_100 或一个 Section_1000
  • 总是Staging_Section_##?如果是这样,只需存储当前子字符串,如果该子字符串与您存储的子字符串不同,则在下一个循环中创建一个新列表并添加当前列表。每次节省时间,以确保您比较之前的变化。

标签: c# list listbox


【解决方案1】:

我会为此使用Dictionary<string, List<string>>。解析的每个“部分”都是一个键,其余部分是值。

Dictionary<string, List<string>> myDict = new Dictionary<string, List<string>>();
foreach (var it in uploadBox.Items)
{
    if (it.ToString().Contains("Section"))
    {
        section = it.ToString().Substring(0, 18);
        found = it.ToString().IndexOf("_");
        section = section.Substring(found + 1);
        sectionNum = section.Substring(8, 2);

        if(!myDict.ContainsKey(sectionNum))
        {
            myDict.Add(sectionNum, new List<string> { someOtherValue });
        }
        else
        {
            myDict[sectionNum].Add(someOtherValue);
        }
    }
}

除非我完全误解了您的问题,否则我认为这是您的动态对象的潜在解决方案。

【讨论】:

  • 如果我们有一个 ...Section_100...,那么 Substring(0,18) 将是一个问题
  • 我同意。我建议拆分 '_' 并加入索引 1 和 2。
【解决方案2】:

你可以这样做:

var sections = new Dictionary<string, List<string>>();

foreach(var it in uploadBox.Items)
{
    var item = it.ToString();

    if(item.Contains("Section"))
    {

        var section = GetSection(item);

        if(!sections.ContainsKey(section))
        {
            sections.Add(section, new List<string>());            
        } 

        sections[section].Add(item);
    }    
}

private string GetSection(string item)
{
    var split = item.Split("_");
    return $"{split[1]}_{split[2]}";    
}

【讨论】:

    【解决方案3】:

    这种任务最好使用正则表达式:

    uploadBox.Items
        .GroupBy(x => Regex.Match(x.ToString(), @"^\w+_Section_(?<section>\d+)").Groups["section"].Value)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      • 2017-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多