I have the following list:
I want to turn these strings into one string, comma separated, but I want to add a character to them first (the @ symbol). The end result should be: @alpha,@beta,@charlie,@delta
What I have right now is a non-LINQ method, but it doesn't seem "clean":
String.Concat("@", String.Join(",@", mylist));
Imagine I need to concatenate on object.Name. Why linq and not string.Join () ? string.Join is better but I think linq makes your code fun, that could be the why! String.Join is better because it uses a StringBuilder and avoids the inherrent O (n^2) performance of repeated concatenation.
List<string> strings = new List<string> () { "ABC", "DEF", "GHI" }; string s = strings.Aggregate ( (a, b) => a + ',' + b); var oCSP = (from P in db.Products select new { P.ProductName }); string joinedString = string.Join (",", oCSP.Select (p => p.ProductName)); Put String.Join into an extension method.
Because the String class implements the generic IEnumerable<T> interface, any string can be queried as a sequence of characters. However, this is not a common use of LINQ. For complex pattern matching operations, use the Regex class. The following example queries a string to determine the number of numeric digits it contains.
It is still perfectly valid for anyone who bumps into this answer while looking for a "not-necessarily-LINQ" solution on Google. Regarding this answer "not useful" in that context is unfair. This can also be used for things other than List <String> s and will call the ToString () method.
string.Join(",", mylist.Select(s => "@" + s));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With