ASP.Net/C# - get distinct values from comma separated string?

sbornstein2 used Ask the Experts™
Hello all,

I think this is easy but I am trying to figure out the best way to do this.  I don't want to use a contains because that may find a partial string in another string and still be valid.

I have a string that has a comma delimter in it for example:

string mystring = "group1, group4, group1"

I only want the distinct values in the string so:

string mystringdis = "group1, group4".

What is the best way to handle this?  I would prefer to use a LINQ statement if there is a way to do it with LINQ.

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Convert the string to an array then use LINQ to get the unique items.
string[] myArray = mystring.split(',');
myArray = myArray.Distinct().ToArray();


I then need to get it back to a string though as it is being used in a IN statement string.  Is there a LINQ statement to get it back to a string?  I am going to test this now but this is definatly what I am looking for. Thanks

string myNewString = String.Join(",", myArray);


thanks so much, I appreciate it.  I should have known this one :)


Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial