Hell.Bent
Hell.Bent

Reputation: 1677

Removing duplicates from Array with C#.NET 4.0 LINQ?

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.

Upvotes: 3

Views: 5778

Answers (5)

Swinkaran
Swinkaran

Reputation: 1255

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();

Upvotes: 0

Volkmar Rigo
Volkmar Rigo

Reputation: 1163

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());

Upvotes: 4

Oleks
Oleks

Reputation: 32333

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()
    );

Upvotes: 4

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391396

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.

Upvotes: 4

Stecya
Stecya

Reputation: 23266

string[] s = found.Split(',').Distinct().ToArray()

Upvotes: 7

Related Questions