在这篇文章Other Post中,我使用List<KeyValuePair<string, string>> IdentityLines = new List<KeyValuePair<string, string>>();
的程序员建议来收集目录的某些文件中的多个字符串值。我现在想要从该列表中删除重复的值。知道如何在C#中做到这一点?感谢
答案 0 :(得分:5)
使用Linq中的Distinct方法。这是一个使用int列表的示例。
Using System.Linq;
List<int> list = new List<int> { 1, 2, 3, 1, 3, 5 };
List<int> distinctList = list.Distinct().ToList();
答案 1 :(得分:2)
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,而不是将其添加到最终列表中。
答案 2 :(得分:0)
我知道这是一个老问题,但这是我如何做到的:
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);