Convert a list into a comma-separated string - c#

My code is as below:
public void ReadListItem()
{
List<uint> lst = new List<uint>() { 1, 2, 3, 4, 5 };
string str = string.Empty;
foreach (var item in lst)
str = str + item + ",";
str = str.Remove(str.Length - 1);
Console.WriteLine(str);
}
Output: 1,2,3,4,5
What is the most simple way to convert the List<uint> into a comma-separated string?

Enjoy!
Console.WriteLine(String.Join(",", new List<uint> { 1, 2, 3, 4, 5 }));
First Parameter: ","
Second Parameter: new List<uint> { 1, 2, 3, 4, 5 })
String.Join will take a list as a the second parameter and join all of the elements using the string passed as the first parameter into one single string.

You can use String.Join method to combine items:
var str = String.Join(",", lst);

Using String.Join:
string.Join<string>(",", lst);
Using LINQ aggregation:
lst .Aggregate((a, x) => a + "," + x);

If you have a collection of ints:
List<int> customerIds= new List<int>() { 1,2,3,3,4,5,6,7,8,9 };
You can use string.Join to get a string:
var result = String.Join(",", customerIds);
Enjoy!

Follow this:
List<string> name = new List<string>();
name.Add("Latif");
name.Add("Ram");
name.Add("Adam");
string nameOfString = (string.Join(",", name.Select(x => x.ToString()).ToArray()));

You can use String.Join for this if you are using .NET framework> 4.0.
var result= String.Join(",", yourList);

You can refer to the below example for getting a comma-separated string array from a list.
Example:
List<string> testList= new List<string>();
testList.Add("Apple"); // Add string 1
testList.Add("Banana"); // 2
testList.Add("Mango"); // 3
testList.Add("Blue Berry"); // 4
testList.Add("Water Melon"); // 5
string JoinDataString = string.Join(",", testList.ToArray());

#{ var result = string.Join(",", #user.UserRoles.Select(x => x.Role.RoleName));
#result
}
I used in MVC Razor View to evaluate and print all roles separated by commas.

Try
Console.WriteLine((string.Join(",", lst.Select(x=>x.ToString()).ToArray())));
HTH

We can try like this to separate list entries by a comma:
string stations =
haul.Routes != null && haul.Routes.Count > 0 ?String.Join(",",haul.Routes.Select(y =>
y.RouteCode).ToList()) : string.Empty;

static void Main(string[] args) {
List<string> listStrings = new List<string>() {"C#", "ASP.NET", "SQL Server", "PHP", "Angular"};
string CommaSeparateString = GenerateCommaSeparateStringFromList(listStrings);
Console.Write(CommaSeparateString);
Console.ReadKey();
}
private static string GenerateCommaSeparateStringFromList(List<string> listStrings){return String.Join(",", listStrings);}
Convert a list of string to a comma-separated string in C#

categories = ['sprots', 'news'];
categoriesList = ", ".join(categories)
print(categoriesList)
This is the output:
sprots, news

You can separate list entities by a comma like this:
//phones is a list of PhoneModel
var phoneNumbers = phones.Select(m => m.PhoneNumber)
.Aggregate(new StringBuilder(),
(current, next) => current.Append(next).Append(" , ")).ToString();
// Remove the trailing comma and space
if (phoneNumbers.Length > 1)
phoneNumbers = phoneNumbers.Remove(phoneNumbers.Length - 2, 2);

You can also override ToString() if your list items have more than one string:
public class ListItem
{
public string string1 { get; set; }
public string string2 { get; set; }
public string string3 { get; set; }
public override string ToString()
{
return string.Join(
","
, string1
, string2
, string3);
}
}
To get a CSV string:
ListItem item = new ListItem();
item.string1 = "string1";
item.string2 = "string2";
item.string3 = "string3";
List<ListItem> list = new List<ListItem>();
list.Add(item);
string strinCSV = (string.Join("\n", list.Select(x => x.ToString()).ToArray()));

You can make use of google-collections.jar which has a utility class called Joiner:
String commaSepString = Joiner.on(",").join(lst);
Or you can use the StringUtils class which has a function called join. To make use of StringUtils class, you need to use common-lang3.jar
String commaSepString=StringUtils.join(lst, ',');
For reference, refer this link Convert Collection into Comma Separated String

Related

C#: How to split a string with a changing prefix

Hello I looked at several post about this topics but no answer could help me.
I extract data about various machines which look like this:
"time, M1.A, M1.B, M1.C, M2.A, M2.B, M2.C, M3.A, M3.B, M3.C"
M1 is the prefix which specifies which machine. A,B,C are attributes of this machine like temperature, pressure, etc.
The output should then look like this:
{{"time", "M1.A", "M1.B", "M1.C"}, {"time", "M2.A",....}}
I know that I could possibly split at "," and then create the list but I was wondering if there is another way to detect if the prefix changed.
Regex.Matches(myList, #"M(?<digit>\d+)\..") //find all M1.A etc
.Cast<Match>() //convert the resulting list to an enumerable of Match
.GroupBy(m => m.Groups["digit"].Value) //find the groups with the same digits
.Select(g => new[] { "time" }.Union(g.Select(m => m.Value)).ToArray());
//combine the groups into arrays beginning with "time"
You mention "the output should then look like this...", but then you mention a list, so I'm going to assume that you mean to make the original string into a list of lists of strings.
List<string> split = new List<string>(s.Split(','));
string first = split[0];
split.RemoveAt(0);
List<List<string>> result = new List<List<string>>();
foreach (var dist in split.Select(o => o.Split('.')[0]).Distinct())
{
List<string> temp = new List<string> {first};
temp.AddRange(split.Where(o => o.StartsWith(dist)));
result.Add(temp);
}
This does the original split, removes the first value (you didn't really specify that, I assumed), then loops around each machine. The machines are created by splitting each value further by '.' and making a distinct list. It then selects all values in the list that start with the machine and adds them with the first value to the resulting list.
Using Regex I created a dictionary :
string input = "time, M1.A, M1.B, M1.C, M2.A, M2.B, M2.C, M3.A, M3.B, M3.C";
string pattern1 = #"^(?'name'[^,]*),(?'machines'.*)";
Match match1 = Regex.Match(input, pattern1);
string name = match1.Groups["name"].Value;
string machines = match1.Groups["machines"].Value.Trim();
string pattern2 = #"\s*(?'machine'[^.]*).(?'attribute'\w+)(,|$)";
MatchCollection matches = Regex.Matches(machines, pattern2);
Dictionary<string, List<string>> dict = matches.Cast<Match>()
.GroupBy(x => x.Groups["machine"].Value, y => y.Groups["attribute"].Value)
.ToDictionary(x => x.Key, y => y.ToList());
Some quick example for you. I think is better to parse it by you own way and have string structure of your Machine-Attribute pair.
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp4 {
class Program {
static void Main(string[] args) {
string inputString = "time, M1.A, M1.B, M1.C, M2.A, M2.B, M2.C, M3.A, M3.B, M3.C";
string[] attrList = inputString.Split(',');
// 1. Get all machines with attributes
List<MachineAttribute> MachineAttributeList = new List<MachineAttribute>();
for (int i = 1; i < attrList.Length; i++) {
MachineAttributeList.Add(new MachineAttribute(attrList[i]));
}
// 2. For each machine create
foreach (var machine in MachineAttributeList.Select(x=>x.Machine).Distinct()) {
Console.Write(attrList[0]);
foreach (var attribute in MachineAttributeList.Where(x=>x.Machine == machine)) {
Console.Write(attribute + ",");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
public class MachineAttribute {
public string Machine { get; }
public string Attribute { get; }
public MachineAttribute(string inputData) {
var array = inputData.Split('.');
if (array.Length > 0) Machine = array[0];
if (array.Length > 1) Attribute = array[1];
}
public override string ToString() {
return Machine + "." + Attribute;
}
}
}

Better way to iterate over several foreach loops together and add it to a datagridview C#

I am trying to get use 3 foreach loops to get single values from powershell and add them in a row. My code is as follows:
string listDomains = "Get-MsolDomain";
string getLicenseInfo = "Get-MsolAccountSku";
string domainsInfo = executeCommand.runAzurePowerShellModule(listDomains, "Name");
string availableLicensesTypes = executeCommand.runAzurePowerShellModule(getLicenseInfo, "AccountSkuId");
string totalLicenses = executeCommand.runAzurePowerShellModule(getLicenseInfo, "ActiveUnits");
string consumedLicenses = executeCommand.runAzurePowerShellModule(getLicenseInfo, "ConsumedUnits");
List<string> licenseTypeArray = new List<string>();
List<string> totalLicenseArray = new List<string>();
List<string> consumedLicenseArray = new List<string>();
foreach (string s in Regex.Split(availableLicensesTypes, "\n"))
{
licenseTypeArray.Add(s);
}
foreach (string v in Regex.Split(totalLicenses, "\n"))
{
totalLicenseArray.Add(v);
}
foreach (string t in Regex.Split(consumedLicenses, "\n"))
{
consumedLicenseArray.Add(t);
}
I was wondering if this can even be done. I was looking at concatenating the three lists and then splitting them but I could not think of anything after concatenating the strings. Any help would be really appreciated.
It is difficult to understand what you're asking here. I think you are saying that you have three sequences:
var s1 = "a b c".Split(' ');
var s2 = "d e f".Split(' ');
var s3 = "g h i".Split(' ');
And you wish to concatenate them "vertically".
You need a zip-concat operation:
public static IEnumerable<string> ZipConcat(IEnumerable<string> xs, IEnumerable<string> ys)
{
return xs.Zip(ys, (x, y) => x + y);
}
And now your problem is easy:
var s4 = ZipConcat(ZipConcat(s1, s2), s3);
foreach(var s in s4)
Console.WriteLine(s);
Produces:
adg
beh
cfi
You could use the AddRange instead of iterating over the items:
licenseTypeArray.AddRange(Regex.Split(availableLicensesTypes, "\n"));
totalLicenseArray.AddRange(Regex.Split(totalLicenses, "\n"));
consumedLicenseArray.AddRange(Regex.Split(consumedLicenses, "\n"));
I hope this is what you meant with easier way. If not please elaborate your question.
You can use this code to avoid using three for loops and shorten the lines of code
licenseTypeArray = Regex.Split(availableLicensesTypes, "\n").ToList();
totalLicenseArray = Regex.Split(totalLicenses, "\n").ToList();
consumedLicenseArray = Regex.Split(consumedLicenses, "\n").ToList();
For displaying this data in a GridView or so, I think you will need just two columns, the first column to list all the license names, the second column to show if it is available or consumed (Boolean value [true or false]).
OK, fine. Please try the following code. First of all define a new entity class like the following.
public class LicenseInfo
{
public string LicenseType { get; set; }
public int TotalLicenesesCount { get; set; }
public int ConsumedLicensesCount { get; set; }
}
Then use the following code:
List<string>licenseTypeArray = Regex.Split(availableLicensesTypes, "\n").ToList();
List<string> totalLicenseArray = Regex.Split(totalLicenses, "\n").ToList();
List<string> consumedLicenseArray = Regex.Split(consumedLicenses, "\n").ToList();
//A generic list of the new entity class that wraps the three properties (columns)
List<LicenseInfo> licensesList = new List<LicenseInfo>();
//concat zip the three lists with a comma-separated for each entry in the new list with this pattern ("License Type, Total Count, Consumed Count").
//Example("Entrprise License,200,50")
List<string> licensesConcatenatedList = licenseTypeArray.Zip(totalLicenseArray.Zip(consumedLicenseArray,
(x, y) => x +","+ y),
(x1,y1) => x1 + "," + y1).ToList();
licensesConcatenatedList.ForEach(t => licensesList.Add(new LicenseInfo
{
LicenseType = t.Split(new char[] { ',' })[0],
TotalLicenesesCount = int.Parse(t.Split(new char[] { ',' })[1]),
ConsumedLicensesCount = int.Parse(t.Split(new char[] { ',' })[2])
}));
Now you have your data in one list of entities that wrap all information you want to display in the gridview, then just bind this new list to the gridview as a data source as usual. You will use the names of the properties as the field names in your GridView.
I hope the idea is clear. Please mark it as answer if this helped you.
Here is a complete code to handle this. I have tested the code and it is working fine. Just copy this code in any aspx page to test. It displays sample data in a gridview after doing the data transformation you're looking for.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SampleTest1
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string> licenseTypeArray = new List<string>() { "Type 1", "Type 2", "Type 3" };
List<string> totalLicenseArray = new List<string>() { "100", "200", "300" };
List<string> consumedLicenseArray = new List<string>() { "50", "100", "150" };
//A generic list of the new entity class that wraps the three properties (columns)
List<LicenseInfo> licensesList = new List<LicenseInfo>();
//concat zip the three lists with a comma-separated for each entry in the new list with this pattern ("License Type, Total Count, Consumed Count").
//Example("Entrprise License,200,50")
List<string> licensesConcatenatedList = licenseTypeArray.Zip(totalLicenseArray.Zip(consumedLicenseArray,
(x, y) => x + "," + y),
(x1, y1) => x1 + "," + y1).ToList();
licensesConcatenatedList.ForEach(t => licensesList.Add(new LicenseInfo
{
LicenseType = t.Split(new char[] { ',' })[0],
TotalLicenesesCount = int.Parse(t.Split(new char[] { ',' })[1]),
ConsumedLicensesCount = int.Parse(t.Split(new char[] { ',' })[2])
}));
GridView1.DataSource = licensesList;
GridView1.DataBind();
}
}
class LicenseInfo
{
public string LicenseType { get; set; }
public int TotalLicenesesCount { get; set; }
public int ConsumedLicensesCount { get; set; }
}
}
I hope this will help you.

How to get filename's prefix ID # into List array with RegEx?

How to get filename's prefix ID # into List array with RegEx? Or alternative method if you know of better one.
I only wants the 111, 222, and 333 values (ID #).
var myList = new List<string>();
myList.Add("foo/0000-0000-0001/111_Age_3_20150518T0800-0400.txt");
myList.Add("foo/0000-0000-0002/222_Bal_3_20120518T0800-0400.txt");
myList.Add("foo/0000-0000-0003/333_DDS_3_20140518T0800-0400.txt");
var filteredFiles2.Select(x => Regex.Match(x, #"^[^\d]+").Value).Distinct();
You can use the Path class to get the filename and then split it:
var filteredFiles = myList.Select(x => System.IO.Path.GetFileNameWithoutExtension(x).Split('_').First()).ToList();
Do you need the Regex function (i.e. class requirement)?
If not, you could just brute force it, like below:
private List<String> myList;
private void Init()
{
myList = new List<string>();
myList.Add("foo/0000-0000-0001/111_Age_3_20150518T0800-0400.txt");
myList.Add("foo/0000-0000-0002/222_Bal_3_20120518T0800-0400.txt");
myList.Add("foo/0000-0000-0003/333_DDS_3_20140518T0800-0400.txt");
}
private string[] filtered()
{
var list = new List<String>();
foreach (var line in myList)
{
var split1 = line.Split('/');
if (split1.Length == 3)
{
var split2 = split1[2].Split('_');
if (split2.Length == 4)
{
list.Add(split2[0]);
}
}
}
return list.ToArray();
}

Can i read an array in one line of code?

Supposed i have an array int[] arr = {1,2,3,4}
I want to convert it into a string.
The result i want it to be like this string a = "1,2,3,4";
so can i have something "string a = arr...." to do it, instead of writing a for loop??
Thanks
As of .NET 4, you can simply do:
var result = string.Join( ",", arr );
In earlier versions,
var result = string.Join( ",", arr.Select( a => a.ToString() ).ToArray() );
You can use String.Join:
int[] arr = new [] { 4, 5, 6, 7 };
string joined = String.Join(",", arr);
See http://msdn.microsoft.com/en-us/library/57a79xd0.aspx for more info.
string result = string.Join(", ", arr.Select(item => item.ToString()).ToArray());
If you can't use .net 4 (I can't yet as our customers don't deploy it), you can use an extension method. This will work then work for all IEnumerable<T>'swith appropriately implemented .ToString() overrides. You can also pick what sort of seperator you want.
Once you have the below, you can just do string s = myenumerable.Seperated(",");
public static class EnumerableExtender
{
public static string Separated<T>(this IEnumerable<T> l, string separator)
{
var sb = new StringBuilder();
var first = true;
foreach (var o in l)
{
if (first) first = false; else sb.Append(separator);
sb.Append(o.ToString());
}
return sb.ToString();
}
}

Convert a IList<int> collection to a comma separated list

Any elegant ways of converting a IList collection to a string of comma separated id's?
"1,234,2,324,324,2"
IList<int> list = new List<int>( new int[] { 1, 2, 3 } );
Console.WriteLine(string.Join(",", list));
You can do:
// Given: IList<int> collection;
string commaSeparatedInts = string.Join(",",collection.Select(i => i.ToString()).ToArray());
// list = IList<MyObject>
var strBuilder = new System.Text.StringBuilder();
foreach(var obj in list)
{
strBuilder.Append(obj.ToString());
strBuilder.Append(",");
}
strBuilder = strBuilder.SubString(0, strBuilder.Length -1);
return strBuilder.ToString();
This will do it
IList<int> strings = new List<int>(new int[] { 1,2,3,4 });
string[] myStrings = strings.Select(s => s.ToString()).ToArray();
string joined = string.Join(",", myStrings);
OR entirely with Linq
string aggr = strings.Select(s=> s.ToString()).Aggregate((agg, item) => agg + "," + item);
List<int> intList = new List<int>{1,234,2,324,324,2};
var str = intList.Select(i => i.ToString()).Aggregate( (i1,i2) => string.Format("{0},{1}",i1,i2));
Console.WriteLine(str);
mstrickland has a good idea on using string builder because of its speed with larger lists. However, you can't set a stringbuilder as a string. Try this instead.
var strBuilder = new StringBuilder();
foreach (var obj in list)
{
strBuilder.Append(obj.ToString());
strBuilder.Append(",");
}
return strBuilder.ToString(0, strBuilder.Length - 1);

Categories

Resources