Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicated elements from a List<String>

Tags:

c#

list

winforms

I would like to remove the duplicate elements from a List. Some elements of the list looks like this:

Book  23
Book  22
Book  19
Notebook 22
Notebook 19
Pen 23
Pen 22
Pen 19

To get rid of duplicate elements i've done this:

List<String> nodup = dup.Distinct().ToList();

I would like to keep in the list just

Book 23
Notebook 22
Pen 23

How can i do that ?

like image 339
Emil Dumbazu Avatar asked Dec 30 '25 20:12

Emil Dumbazu


2 Answers

you can do someting like

string firstElement = dup.Distinct().ToList().First();

and add it to another list if you want.

like image 142
Dipesh Bhatt Avatar answered Jan 01 '26 10:01

Dipesh Bhatt


It's not 100% clear what you want here - however...

If you want to keep the "largest" number in the list, you could do:

List<string> noDup = dup.Select(s => s.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries)
        .Select(p => new { Name=p[0], Val=int.Parse(p[1]) })
        .GroupBy(p => p.Name)
        .Select(g => string.Join(" ", g.Key, g.Max().ToString()))
        .ToList();

This would transform the List<string> by parsing the numeric portion into a number, taking the max per item, and creating the output string as you have specified.

like image 33
Reed Copsey Avatar answered Jan 01 '26 09:01

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!