I want the output as the below string format using LINQ.
["providerZip","providerType"]
Can anyone please tell me, how to concatenate the two strings in an array using LINQ ?
using System.Linq;
using System;
public class Program
{
public static void Main()
{
string[] words = { "providerZip", "providerType" };
var res = words.Aggregate((current, next) => current + ", " + next);
Console.WriteLine(res);
}
}
You can try like this:
string[] str = { "providerZip", "providerType" };
var res = str.Aggregate((cur, nxt) => cur + ", " + nxt);
What you actually need to Json Serialization of a list of strings. That'd be the right way to go. For Json I've used Json.NET in my example below, you can use the .NET json serializer as well.
But, if really don't want that, you can still manually create that string using string.Join and a little Linq.
//input strings
var str = new List<string>{ "providerZip", "providerType" };
//with json serialization with Json.NET
//using Newtonsoft.Json; <= install Json.Net NuGet package
var jsonString = JsonConvert.SerializeObject(str); //=> ["providerZip","providerType"]
//with plain string manipulation + Linq
var outputString = "[" + string.Join(",", str.Select(s => "\"" + s + "\"")) + "]"; //=> ["providerZip","providerType"]
string.Joinis usually the best way to join an IEnumerable into a comma separated list. You don't need LINQ for that. If this is even your question.list[0] + list[1]. I KNOW it's not LINQ, but I just couldn't resist