Removing duplicates from an array using C # .NET 4.0 LINQ?

I have this C # code that builds a comma-separated string of matches for a service:

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

The output looks like this: aaa, bbb, ccc, aaa, 111,111, ccc

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

Also, any way to remove duplicates without changing the order?

I found this sample code in another post, but I don’t know exactly how to apply it:

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

Thank.

+3
source share
5 answers
string[] s = found.Split(',').Distinct().ToArray()
+5
source

Rewrite the code that builds the result for immediate output.

so rewrite this:

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

For this:

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

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

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

.ToArray() , .NET..NET 4.0 string.Join(...) IEnumerable<string>, .

+4

:

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

this may be one of the possible solutions:

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());
+4
source

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

Source: https://habr.com/ru/post/1794413/


All Articles