Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: String.Join a list but add a character to that string beforehand

I have the following list:

  • alpha
  • beta
  • charlie
  • delta

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));
like image 370
michael Avatar asked Jun 07 '11 18:06

michael


People also ask

Why LINQ and not string join()?

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.

How to join strings in List<String>?

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.

Can I use LINQ to query a string?

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.

Is LINQ not useful anymore?

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.


1 Answers

string.Join(",", mylist.Select(s => "@" + s));
like image 124
n8wrl Avatar answered Oct 26 '22 10:10

n8wrl