在此帖子中Other Post我使用List<KeyValuePair<string, string>> IdentityLines = new List<KeyValuePair<string, string>>();
的程序员建议来收集目录中某些文件中的多个字符串值。我现在想要从该列表中删除重复值。任何想法如何在C#中做到这一点?谢谢搜索并删除列表中的重复项
回答
static List<T> RemoveDuplicates<T>(List<T> inputList)
{
Dictionary<T, int> uniqueStore = new Dictionary<T, int>();
List<T> finalList = new List<T>();
foreach (string currValue in inputList)
{
if (!uniqueStore.ContainsKey(currValue))
{
uniqueStore.Add(currValue, 0);
finalList.Add(currValue);
}
}
return finalList;
}
http://www.kirupa.com/net/removingDuplicates.htm
如果你想返回一个IEnumerable
而是改变你的返回类型IEnumerable<T>
和yield
return
currValue,而不是将它添加到最后名单。
在该链接上发布此行后列表
我想你想'foreach(结果中的字符串s)',根据你提供的错误。 – 2010-08-10 21:05:07
嗨罗伯特 - 如果我这样做,那么我怎么写s的价值? s没有s.value,我可以在fs.Write()中使用; – Josh 2010-08-10 21:07:37
使用与Linq一起发现的Distinct方法。这里是一个使用int列表的例子。
Using System.Linq;
List<int> list = new List<int> { 1, 2, 3, 1, 3, 5 };
List<int> distinctList = list.Distinct().ToList();
我知道这样一个老问题,但在这里就是我如何做到这一点:
var inputKeys = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("myFirstKey", "one"),
new KeyValuePair<string, string>("myFirstKey", "two"),
new KeyValuePair<string, string>("mySecondKey", "one"),
new KeyValuePair<string, string>("mySecondKey", "two"),
new KeyValuePair<string, string>("mySecondKey", "two"),
};
var uniqueKeys = new List<KeyValuePair<string, string>>();
//get rid of any duplicates
uniqueKeys.AddRange(inputKeys.Where(keyPair => !uniqueKeys.Contains(keyPair)));
Assert.AreEqual(inputKeys.Count(), 5);
Assert.AreEqual(uniqueKeys.Count(), 4);
- 1. VBA - 搜索并删除重复项
- 2. 删除列表中的重复项
- 3. 删除列表中的重复项
- 4. 从Python列表中删除重复项
- 5. 从Django列表中删除重复项
- 6. odoo one2many列表中删除重复项
- 7. 从Python列表中删除重复项
- 8. 从C++列表中删除重复项
- 9. Python从列表中删除重复项?
- 10. 搜索并从列表框中删除项目
- 11. 组合两个列表并删除重复项,而不删除重复项在原始列表
- 12. mysql按列A搜索重复项并按其他条件删除
- 13. 在Python中创建列表并删除重复项
- 14. 删除重复的列表项从列表的列表清单
- 15. 使用其他列表的重复项删除项目列表
- 16. C#从包含列表的列表中删除重复项
- 17. 删除Python中的重复项Pandas DataFrame不删除重复项
- 18. 删除阵列中的重复项(C++)
- 19. 删除列中的重复项R
- 20. 删除TSQL列中的重复项
- 21. SQL删除某列中的重复项
- 22. 使用索引而不是值来搜索时从列表中删除重复
- 23. SQL删除表中的重复项
- 24. 删除表中的重复项
- 25. 删除数据表中的重复项
- 26. 删除大型表中的重复项
- 27. 删除大MySql表中的重复项
- 28. 查找并删除重复的索引?
- 29. C#如何过滤列表并删除重复项?
- 30. 比较两个通用列表并删除重复项
参见http://stackoverflow.com/questions/47752/remove-duplicates-from-a-listt-in- c – 2010-08-10 20:55:45