Solved

C# - How to remove duplicates from a string

Posted on 2014-10-29
4
420 Views
Last Modified: 2014-10-29
Hi..
I have a string of email addreses with duplicates like this.
How can I remove the dups.. maybe use Split and LINQ?

"jon@abc.com; mary@xyz.com ; jon@ABC.com;  MARY@xyZ.com"

I want to return
"jon@abc.com; mary@xyz.com"

thx
0
Comment
Question by:JElster
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 23

Accepted Solution

by:
Snarf0001 earned 300 total points
ID: 40412149
Give this a shot:

            var dupes = "jon@abc.com; mary@xyz.com ; jon@ABC.com;  MARY@xyZ.com";
            dupes = string.Join(";", dupes.Split(new char[] { ';'}, StringSplitOptions.RemoveEmptyEntries).Select(d=> d.ToLower().Trim()).Distinct());

Open in new window

0
 
LVL 15

Assisted Solution

by:David L. Hansen
David L. Hansen earned 200 total points
ID: 40412157
Sure.  When you use the Split function the result is an array of strings (for you just use the semicolon as the delimiter)...like this:
string[] emails = yourEmailList.Split(';');
string[] uniqueEmails = emails.Distinct().ToArray();

Open in new window

0
 
LVL 23

Expert Comment

by:Snarf0001
ID: 40412172
You have to convert to lowercase as per my example, otherwise it's not going to trim out the case differences.
0
 
LVL 15

Expert Comment

by:David L. Hansen
ID: 40412185
Yes, in my code just add a ".ToLower" right inbetween "yourEmailList" and "Split".  Thanks Snarf.
string[] emails = yourEmailList.ToLower.Split(';');

Open in new window

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question