- Home /
LINQ Find String Duplicates in List
I am trying to prevent name duplicates in a List, but with no luck so far.
I have a list of entries and each entry has a name (e.g. entries: "file", "file1", "someFile", "anotherFile"). Whenever I create new entry I add it to the entry List. But I don't want to add new entry with the same name.
I have a file that I just created (e.g. name: "file"). How do I find all name duplicates and make it something like this at the end: "file2"? Sorry if the question is a bit vague.
I tried to use LINQ and Regex, but I'm kind of new to those things so not sure what I'm doing..
Answer by Arthur_Kenichi · Nov 29, 2018 at 01:10 AM
If you don't wanna add a duplicate in the first place (or if you want to have duplicates discarded when trying to add them), you can use the C# HashSet Class:
"The HashSet class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order."
HashSet.Add(T) Method: "Returns Boolean true if the element is added to the HashSet object; false if the element is already present."
Then if the Add method returns false, you can try to add another name.
If you want to check all the other values with LINQ, there are a lot of examples in the internet, I'll find one now for you: C# LINQ find duplicates in List "Using LINQ, from a List, how can I retrieve a list that contains entries repeated more than once and their values?[...] The easiest way to solve the problem is to group the elements based on their value, and then pick a representative of the group if there are more than one element in the group. In LINQ, this translates to:
var query = lst.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(y => y.Key)
.ToList();
"
I'm a little bit off of LINQ too, but from what I understand: GroupBy(x => x)
means "create sub 'lists' of the same object"; then Where(g => g.Count() > 1)
discards all the "sub lists" which have only one object, which means they didn't repeat values; Select(y => y.$$anonymous$$ey)
will get a "list" (Enumerable) of the "$$anonymous$$eys" that represent the each of the ''sub lists" which have repeated values from Where
. That means the item repeating in each group from GroupBy(x => x)
that had Count > 1
. And finally .ToList();
turns Enumerable into List again, as each LINQ function turned the List into a Enumerable Class.