MiBol
MiBol

Reputation: 2125

How create a string of distinct values from an Array (Including additional chars)

I have a simple question for the LINQ experts. I want create a single string based in an Array:

return String.Join(",", (from string val 
     in arrayValues
     select new { value = "%" + val.ToString() + "%" })
     .Distinct().ToArray());

This code give an error, but I cannot found the way how fix the issue.

Example; I want to send {"1","2","3","4"} and my expected result should be something like that: "%1%,%2%,%3%,%4%"

Any help will be welcome!

Upvotes: 1

Views: 85

Answers (2)

Lee
Lee

Reputation: 144136

It's not clear from your example why you need Distinct but you can do:

return string.Join(",", arrayValues.Distinct().Select(s => "%" + s + "%"));

or

var values = from val in arrayValues.Distinct() select "%" + val + "%";
return string.Join(",", values);

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564413

You can just use:

return String.Join(",", arrayValues.Distinct().Select(v => "%" + v + "%"));

If you always will have at least one element, you could also use:

return "%" + string.Join("%,%", arrayValues.Distinct()) + "%";

Upvotes: 2

Related Questions