【问题标题】:C# Problem with duplicate list entries重复列表条目的 C# 问题
【发布时间】:2011-09-16 03:41:30
【问题描述】:

大家好,我有一个程序,我正在将所有行加载到一个文本框中,并将它们从字符 : 中拆分出来

它工作正常,但它会复制它。我得到的输出是:

ID: 1NAME: Stone
ID: 1NAME: Stone
ID: 2NAME: Grass
ID: 2NAME: Grass
ID: 3NAME: Dirt
ID: 3NAME: Dirt

什么时候输出应该是:

ID: 1NAME: Stone
ID: 2NAME: Grass
ID: 3NAME: Dirt

我的代码是:

    foreach (String line in File.ReadAllLines("item.ids"))
    {
        items = line.Split(':');


        foreach (String part in items)
        {
            addToList(specs, "ID: "+line.Split(':').First() + "NAME: "+line.Split(':').Last() );
        }
    }

我做错了什么?

【问题讨论】:

  • 请提供 addToList() 和输入

标签: c# arrays split duplicates


【解决方案1】:

我认为你需要放松每个人的内在。 不过,请保留对 addToList 的调用

// for every line in the file....
foreach (String line in File.ReadAllLines("item.ids"))
{
   //get the parts by splitting the line on the colon
   items = line.Split(':');

   //for every item in the parts (there are two parts, according to your code)
   // so this will loop twice--adding your item twice
   foreach (String part in items)
   {

     // you are splitting again, and this is not necessary
     // you could just call items.First() or items[0]
     // and items.Last() or items[1]
     addToList(specs, "ID: "+ line.Split(':').First() + 
                      "NAME: "+line.Split(':').Last() );
   }
 }

我会做这样的事情来修复它:

foreach (string line in File.ReadAllLines("item.ids"))
{
   items = line.Split(':');
   addToList(specs, "ID: "  + items.First() + 
                    "NAME: "+ items.Last() );
}

【讨论】:

    【解决方案2】:

    每个循环都是你的第二个。不需要:

    foreach (String line in File.ReadAllLines("item.ids"))
    {
        items = line.Split(':');
        addToList(specs, "ID: "+line.Split(':').First() + "NAME: "+line.Split(':').Last() );
    
    }
    

    如果你查看你的代码,你没有使用part,而是循环来自Split(':')的结果,这给你一个长度为2的字符串数组。

    【讨论】:

      【解决方案3】:

      您是否确保您正在阅读的文件中没有重复的行或行上的条目?

      如果您插入HashSet<string>,或在现有列表上运行 LINQ Distinct() 查询,那么您将避免最终结果中出现重复。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-17
        • 1970-01-01
        • 2012-12-06
        • 1970-01-01
        • 2014-12-09
        • 2011-10-01
        • 1970-01-01
        相关资源
        最近更新 更多