C# 重复列表条目的问题
嘿伙计们,我正在编写一个程序,我正在将所有行加载到文本框中,并将它们从 char :
中分离出来
。它工作正常,但它会重复它。我得到的输出是:
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() );
}
}
我做错了什么?
Hey guys i'm having a program and I am loading all lines inside a text box and split them from the char :
It works fine and all but it duplicates it. The output I get is:
ID: 1NAME: Stone
ID: 1NAME: Stone
ID: 2NAME: Grass
ID: 2NAME: Grass
ID: 3NAME: Dirt
ID: 3NAME: Dirt
When the output should be:
ID: 1NAME: Stone
ID: 2NAME: Grass
ID: 3NAME: Dirt
My code is:
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() );
}
}
What am i Doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你需要放松每个人的内心。
保留对 addToList 的调用,尽管
我会执行类似的操作来修复它:
i think you need to loose the inner for each.
keep the call to addToList, though
I would do something like this to fix it:
这是每个循环的第二个。这是不需要的:
如果您查看代码,您不会使用
part
,而是循环Split(':')
的结果,它为您提供了一个长度的字符串数组2.It's your second for each loop. It's not needed:
If you look at your code, your not using
part
but are looping the results fromSplit(':')
which is giving you a string array of length 2.您是否确保正在读取的文件中没有重复的行或行?
如果您插入到
HashSet
中,或者在现有列表上运行 LINQ Distinct() 查询,那么您将避免最终结果中出现重复。Have you ensured that you do not have duplicate lines or entries on lines in the file you are reading in?
If you insert into a
HashSet<string>
, or run a LINQ Distinct() query on your existing list then you will avoid duplicates in the final result.