简体   繁体   中英

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM