Convert a IList<int> collection to a comma separated list - c#

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

Related

c# Get only numbers from list of strings which contain numbers and words

I have a list of strings (word--number) ex (burger 5$). I need to extract only numbers from every string in list and make new int list.
There are several ways to do that, Regex and Linq for example.
For short string you can use Linq, for example:
public static void Main()
{
var myStringValue = "burger 5$";
var numbersArray = myStringValue.ToArray().Where(x => char.IsDigit(x));
foreach (var number in numbersArray)
{
Console.WriteLine(numbersArray);
}
}
If you take a look at the Regex.Split, numbers article.
You'll find the answer in there. Modified code might look like
var source = new List<string> {
"burger 5$",
"pizza 6$",
"roll 1$ and salami 2$"
};
var result = new List<int>();
foreach (var input in source)
{
var numbers = Regex.Split(input, #"\D+");
foreach (string number in numbers)
{
if (Int32.TryParse(number, out int value))
{
result.Add(value);
}
}
}
Hope it helps.
Petr
Using linq and Regex:
List<string> list = new List<string>(){"burger 5$","ab12c","12sc34","sd3d5"};
Regex nonDigits = new Regex(#"[^\d]");
List<string> list2 = list.Select(l => nonDigits.Replace(l, "")).ToList();
You can take a look and also solve the problem with this code:
List<string> word_number = new List<string>();
List<int> number = new List<int>();
word_number.Add("burger 5$");
word_number.Add("hamburger 6$");
word_number.Add("burger 12$");
foreach (var item in word_number)
{
string[] parts = item.Split(' ');
string[] string_number = parts[1].Split('$');
number.Add(Convert.ToInt16(string_number[0]));
Console.WriteLine(string_number[0]);
}

Concat all strings inside a List<List<string>> using LINQ

My question is almost same as this one, but the List dimension is n.
How to concat all strings inside a List<List<List...<string>> (n dimension list) using LINQ ?
NOTE: Interested for both cases, n is known or unknown
Since the linked question is tagged as c# so i add this answer with c# code.
If the number of nested lists are known You have to use SelectMany() over and over to unwrap all the nested lists to sequence of chars. then make string out of that sequence.
List<List<List<string>>> nestedList = new List<List<List<string>>>();
var result = new string(nestedList.SelectMany(x => x).SelectMany(x => x).SelectMany(x => x).ToArray());
If the number of nested lists are not known you have to use reflection, since the type is not known. I didnt used reflection directly but actually dynamic type does. The performance would be terrible here of course ;) but it does what you want.
using Microsoft.CSharp.RuntimeBinder;
//...
private static string ConcatAll<T>(T nestedList) where T : IList
{
dynamic templist = nestedList;
try
{
while (true)
{
List<dynamic> inner = new List<dynamic>(templist).SelectMany<dynamic, dynamic>(x => x).ToList();
templist = inner;
}
}
catch (RuntimeBinderException)
{
List<object> l = templist;
return l.Aggregate("", (a, b) => a + b);
}
}
Here is the test
private static void Main(string[] args)
{
List<List<List<string>>> nestedList = new List<List<List<string>>>
{
new List<List<string>> {new List<string> {"Hello "}, new List<string> {"World "}},
new List<List<string>> {new List<string> {"Goodbye "}, new List<string> {"World ", "End "}}
};
Console.WriteLine(ConcatAll(nestedList));
}
Outputs:
Hello World Goodbye World End
Update:
After a bit fiddling i ended up this implementation. maybe better without try catch.
private static string ConcatAll<T>(T nestedList) where T : IList
{
dynamic templist = nestedList;
while (templist.Count > 0 && !(templist[0] is char?))
{
List<dynamic> inner = new List<dynamic>(templist).SelectMany<dynamic, dynamic>(x =>
{
var s = x as string;
if (s != null)
{
return s.Cast<dynamic>();
}
return x;
}).ToList();
templist = inner;
}
return new string(((List<object>) templist).Cast<char>().ToArray());
}
Another solution could be using a recursive method to flatten all your lists:
static IEnumerable<string> Flatten(IEnumerable enumerable)
{
foreach (object el in enumerable)
{
if (enumerable is IEnumerable<string>)
{
yield return (string) el;
}
else
{
IEnumerable candidate = el as IEnumerable;
if (candidate != null)
{
foreach (string nested in Flatten(candidate))
{
yield return nested;
}
}
}
}
}
With this method you can concat all the strings this way:
List<List<List<string>>> nestedList = new List<List<List<string>>>
{
new List<List<string>> {new List<string> {"Hello "}, new List<string> {"World "}},
new List<List<string>> {new List<string> {"Goodbye "}, new List<string> {"World ", "End "}}
};
Console.WriteLine(String.Join(" ",Flatten(nestedList)));
This idea was taken from this post.

Convert a list into a comma-separated string

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

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

an array question

i have an array below
string stringArray = new stringArray[12];
stringArray[0] = "0,1";
stringArray[1] = "1,3";
stringArray[2] = "1,4";
stringArray[3] = "2,1";
stringArray[4] = "2,4";
stringArray[5] = "3,7";
stringArray[6] = "4,3";
stringArray[7] = "4,2";
stringArray[8] = "4,8";
stringArray[9] = "5,5";
stringArray[10] = "5,6";
stringArray[11] = "6,2";
i need to transform like below
List<List<string>> listStringArray = new List<List<string>>();
listStringArray[["1"],["3","4"],["1","4"],["7"],["3","2","8"],["5","6"],["2"]];
how is that possible?
I think what you actually want is probably this:
var indexGroups = x.Select(s => s.Split(',')).GroupBy(s => s[0], s => s[1]);
This will return the elements as a grouped enumeration.
To return a list of lists, which is what you literally asked for, then try:
var lists = x.Select(s => s.Split(',')).GroupBy(s => s[0], s => s[1])
.Select(g => g.ToList()).ToList();
There's no shorthand like that. You'll have to break into a loop and split each array and add to the list.
Non LINQ version (I must admit its much uglier, but you may have no choice)
var index = new Dictionary<string, List<string>>();
foreach (var str in stringArray) {
string[] split = str.Split(',');
List<string> items;
if (!index.TryGetValue(split[0], out items)) {
items = new List<string>();
index[split[0]] = items;
}
items.Add(split[1]);
}
var transformed = new List<List<string>>();
foreach (List<string> list in index.Values) {
transformed.Add(list);
}

Categories

Resources