Reputation: 1901
In this post Other Post I used the programmers suggestion of List<KeyValuePair<string, string>> IdentityLines = new List<KeyValuePair<string, string>>();
to collect multiple string values within certain files of a directory. I now want to remove the duplicate values from that list. Any idea how I can do that in C#? Thanks
Upvotes: 1
Views: 1539
Reputation: 717
I know this an old question, but here's how I do this:
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);
Upvotes: 0
Reputation: 180787
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
If you want to return an IEnumerable
instead, change your return type to IEnumerable<T>
and yield
return
currValue instead of adding it to the final list.
Upvotes: 2
Reputation: 4867
Use the Distinct method that is found with Linq. Here is an example using a list of ints.
Using System.Linq;
List<int> list = new List<int> { 1, 2, 3, 1, 3, 5 };
List<int> distinctList = list.Distinct().ToList();
Upvotes: 5