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

sbornstein2
sbornstein2 used Ask the Experts™
on
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.

Thanks
Comment
Watch Question

Do more with

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

Author

Commented:
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

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

Author

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

mystring.split(',',StringSplitOptions.RemoveEmptyEntries).Distinct();

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