1

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!

1
  • Are you going to make us guess what the error is? Commented Jun 17, 2014 at 22:12

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

I still feel very familiar with the VB.NET. I not saw this workaround in C#.
2

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()) + "%";

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.