【问题标题】:How do I join the data from multiple excel cells to make one list and then remove the duplicates?如何将多个 Excel 单元格中的数据合并为一个列表,然后删除重复项?
【发布时间】:2017-08-24 03:06:57
【问题描述】:

我想从多个 Excel 单元格中获取数据并将其连接起来,使其成为一个大字符串。

单元格 1 和 2 中的原始字符串示例:

单元格1:

the_red_bucket_01, the_blue_duck_01,_the green_banana_02, the orange_bear_01

单元格2:

the_purple_chair_01, the_blue_coyote_01,_the green_banana_02, the orange_bear_01

我希望新列表看起来像这样,每个项目都是列表中自己的字符串对象。一旦数据加入一个大列表,我想将列表中的每个项目分隔成它自己的对象,方法是在逗号后分隔每个项目:

the_red_bucket_01
the_blue_duck_01
the green_banana_02
the orange_bear_01
the_red_chair_01
the_blue_coyote_01
the green_banana_02
the orange_bear_01

然后我想删除重复项,以便控制台只显示每个项目的 1,无论它们有多少。

现在我的代码将每个单元格视为两个单独的列表,尽管列表中的每个对象都是独立的。

例如,如果我想要列表中的第一项,它会返回 cell1 和 cell2 中的第一项,而我只想要一个大列表并返回一个项目。 我似乎无法让我的 foreach/if 语句起作用。 .

 List<string> fn = new List<string>();

                foreach (Excel.Range itemo in xlRng)
                {
                    string itemString = (string)itemo.Text;

                    fn.AddRange((from each in itemString.Split(',')
                                 select each.Trim()).ToArray<string>());

                }
                foreach (string combo in fn.Distinct())
                {

                    Console.WriteLine(combo);
                }

【问题讨论】:

    标签: c# excel visual-studio list


    【解决方案1】:

    为每个单元格创建另一个列表,这样之前的项目就会消失。因为您将变量命名为 fn 并不会使其在每次迭代中都相同。 new 操作员每一步都会创建一个新的引用。 要创建一个持久列表,只需将列表初始化移动到foreach 之前。

    List<string> fn = new List<string>();
    foreach (Excel.Range item in xlRng){...}
    

    在foreach 中,使用list 的AddRange 函数将split 函数的结果相加。 这就是你得到一个大名单的方式。

    【讨论】:

    • 我明白你在说什么,这很有意义,谢谢!只是想知道 AddRange 函数的示例是什么。我用谷歌搜索过的东西,我不确定要使用哪些变量。
    • 我编辑了我的代码,但它仍然返回有重复的两个列表
    • 将第二个 foreach 移到第一个之外。
    • 试过了,编辑后的代码,它仍然返回相同的值:(。我知道它将两个单元格视为单独列表的原因是因为当我这样做时 ... fn.First(); 得到列表的第一个值,它将 Cell1 中的第一项和 Cell2 中的第一项一起返回
    猜你喜欢
    • 2018-04-10
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多