3

I have this c# code that builds a string of comma seperated matches for a service:

for (m = r.Match(site); m.Success; m = m.NextMatch())
{
     found = found + "," + m.Value.Replace(",", "");
}
return found;

Output looks like: aaa,bbb,ccc,aaa,111,111,ccc

Now that code is on .NET 4.0 How can I use C# LINQ to remove duplicates?

Also, Any way to remove duplicates without changing order?

I found this sample code in another post, but not sure exactly how to apply it:

int[] s = { 1, 2, 3, 3, 4}; 
int[] q = s.Distinct().ToArray(); 

Thanks.

1
  • Well, first put the strings you find into an array, see if that helps. You're building up a long string, that won't make it easy to find or remove the duplicates. Commented Feb 24, 2011 at 11:44

5 Answers 5

7
string[] s = found.Split(',').Distinct().ToArray()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. And in 4.0, to return s as a single comma sperated string now?
4

Rewrite the code that builds the result to output it directly.

ie. rewrite this:

for (m = r.Match(site); m.Success; m = m.NextMatch())
{
     found = found + "," + m.Value.Replace(",", "");
}
return found;

To this:

return (from Match m in r.Matches(site)
        select m.Value.Replace(",", "")).Distinct().ToArray();

This will return an array. If you still want it back as a string:

return string.Join(", ", (from Match m in r.Matches(site)
        select m.Value.Replace(",", "")).Distinct().ToArray());

You may or may not be able to remove the last .ToArray() from the last code there depending on the .NET runtime version. .NET 4.0 string.Join(...) can take an IEnumerable<string>, whereas previous versions requires an array.

Comments

4

This will return a string of comma seperated values without duplicates:

var result = string.Join(",",
    r.Matches(site)
        .Cast<Match>()
        .Select(m => m.Value.Replace(",", string.Empty))
        .Distinct()
    );

1 Comment

For .NET before 4.0, you need to add .ToArray() after distinct.
4

this could be one possible solution:

var data = new List<string>();
for (m = r.Match(site); m.Success; m = m.NextMatch())
  data.Add(m.Value.Replace(",", ""));
return String.Join(",", data.Distinct().ToArray());

Comments

0

You can achieve this in a single LINQ query

string strSentence = "aaa,bbb,ccc,aaa,111,111,ccc";
List<string> results = (from w in strSentence.Split(',') select w).Distinct().ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.