Convert List<int> to delimited string list [duplicate] - c#

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
most elegant way to return a string from List<int>
I'm not sure the easiest way to do this. I simply want to add a ; between each value and spit it out as one string. I don't see that you can do this with ToString(). I'd have to loop through and create a stringbuilder and append & add a ";".

UPDATED to use List<int> instead of List<string>
Use string.Join:
List<int> data = ..;
var result = string.Join(";", data); // (.NET 4.0+)
var result = string.Join(";", data.Select(x => x.ToString()).ToArray()); // (.NET 3.5)

string.Join(";", myList.ToArray());

Just use the join
string combinedString = String.Join(";", arrayName);

List<String> list = new List<String>() { "A", "B", "C", "D", "E" };
String joindString1 = String.Join(";", list.ToArray());
String joindString2 = list.Aggregate((s1, s2) => s1 + ";" + s2);

You can also use Enumerable.Aggregate which can give extra flexibility.
var data = new List<int> { 1,2,3 };
var sb = new StringBuilder(100);
// do some other stuff with sb
sb = data.Aggregate(sb, (b, d) => b.Append(d).Append(';'));
if( data.Count > 0 ) sb.Length--;
//do some more stuff with sb
var str = sb.ToString();

Related

Is there a way to concatenate a piece of string to all string in a collection? [duplicate]

I am using C# and .Net 4.0.
I have a List<string> with some values, say x1, x2, x3. To each of the value in the List<string>, I need to concatenate a constant value, say "y" and get back the List<string> as x1y, x2y and x3y.
Is there a Linq way to do this?
List<string> yourList = new List<string>() { "X1", "Y1", "X2", "Y2" };
yourList = yourList.Select(r => string.Concat(r, 'y')).ToList();
list = list.Select(s => s + "y").ToList();
An alternative, using ConvertAll:
List<string> l = new List<string>(new [] {"x1", "x2", "x3"} );
List<string> l2 = l.ConvertAll(x => x + "y");
You can use Select for that
var list = new List<string>(){ "x1", "x2" };
list = list.Select(s => s + "y").ToList();

string and arrays manipulation c#

Here is the code and it is working fine for a single input string
string[] stop_word = new string[]
{
"please",
"try",
"something",
"asking",
"-",
"(", ")",
"/",
".",
"was",
"the"
};
string str = "Please try something (by) yourself. -befor/e asking";
foreach (string word in stop_word)
{
str = str.ToLower().Replace(word, "").Trim();
}
and the output is by yourself before
and now I want to have
string str[] = new string[]
{
"Please try something-by yourself. before (CAD) asking/",
"cover, was adopted. The accuracy (of) the- change map was"
};
and also may be the number of strings is greater than 2 then how to alter this above code to display the str array or store in a text file or database.
Please help with acknowledgements. Thanks
The code for single string need to be put inside a loop for string array
List<string> result = new List<string>();
for(int i =0; i<str.Length; i++)
{
foreach (string word in stop_word)
{
str[i] = str[i].ToLower().Replace(word, "").Trim();
str[i] = Regex.Replace(str[i], #"\s+", " ");
}
result.Add(str[i]);
}
foreach(string r in result)
{
//this is to printout the result
Console.WriteLine(r);
}
You can try it here: https://dotnetfiddle.net/wg83gM
EDIT:
Use regex to replace multiple spaces with one single space
Here is an easy to understand way to do it:
List<string> list = new List<string>();
foreach (string text in str)//loops through your str array
{
string newText =text;
foreach (string word in stop_word) //loops through your word array
{
newText = newText.ToLower().Replace(word, "").Trim();
}
list.Add(newText); //store the results in a list
}
Here is a working Demo
Does this work as you expect?
var results =
str
.Select(x => stop_word.Aggregate(x, (a, y) => a.ToLower().Replace(y, "").Trim()))
.ToArray();
I used this input:
string[] str = new string[]
{
"Please try something-by yourself. before (CAD) asking/",
"cover, was adopted. The accuracy (of) the- change map was"
};
string[] stop_word = new string[]
{
"please", "try", "something", "asking", "-", "(", ")", "/", ".", "was", "the"
};
I got this output:
by yourself before cad
cover, adopted accuracy of change map
You can use Select() for this.
var results = str.Select(x => {
foreach (string word in stop_word)
{
x = x.ToLower().Replace(word, "").Trim();
}
return x;
}).ToList(); // You can use ToArray() if you wish too.
...
foreach(string result in results)
{
Console.WriteLine(result);
}
Result:
by yourself before cad
cover, adopted accuracy of change map

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

How to use LINQ select something contain string[]

How to use linq to select something fit the conditions below,
I want select the words JUST contains the string in ArStr[], i.e. a,b,c
In the Wordslist, "aabb" don't contain "c", "aacc" don't contain "b", "aabbccd" contain "d".
So they are not the words I want.
Please help.
Wordslist :
aabb
aacc
aaabbcc
aabbbcc
aabbccd
ArStr[] :
"a"
"b"
"c"
Expected Query:
aaabbcc
aabbbcc
IEnumerable<Word> Query =
from Word in Wordslist
where
Word.Value.Contains(ArStr[0]) // 1
&& Word.Value.Contains(ArStr[1]) // 2
&& Word.Value.Contains(ArStr[2]) // 3
select Word;
You can construct a set of white-list characters and then filter those words that are set-equal with that white-list (ignoring duplicates and order).
var chars = new HashSet<char>(ArStr); // Construct white-list set
var query = from word in wordsList
where chars.SetEquals(word) // Word must be set-equal with white-list
select word;
or
var query = wordsList.Where(chars.SetEquals);
As you've probably noticed, the query you've written does return "aabbccd", because that string contain "a", it contains "b", and it contains "c".
Assuming that ArStr can only contain one-character strings, and you want to return strings that contain only the specified characters, so you should say (adapted from Ani's answer):
var chars = new HashSet<char>(ArStr.Select(s => s[0]));
var query = wordslist.Where(w => chars.SetEquals(w.Value));
However, if the ArStr elements could be more than one character long, the problem needs to be better defined, and the solution will be more complicated.
Use this method to evaluate a word if it passes your condition or not:
bool HasValidCharacters(string word)
{
var allowedCharacters = new List<string> { "a", "b", "c" };
return string.Join("", word.GroupBy(c => c)
.Select(g => g.Key)
.OrderBy(g => g))
.Equals(string.Join("", allowedCharacters.OrderBy(c => c)));
}
Then simply call the method to get the required list:
var words = new List<string> { "aabb", "aacc", "aaabbcc", "aabbbcc", "aabbccd" };
var matchingWords = words.Where(HasValidCharacters);
You could try this:
List<String> words = new List<string> { "aabb", "aacc", "aaabbcc", "aabbbcc", "aabbccd" };
List<string> allowed = new List<string> { "a", "b", "c" };
var lst = words.Where(word => allowed.All(a => word.Contains(a) && !Regex.IsMatch(word, "[^" + string.Join("", allowed) + "]"))).ToList();
Just another way to implement it.
I think you can use String.Trim Method (Char()) on each element , then the empty element is you want .
var arr = new string[] { "aabb", "aacc", "aaabbcc", "aabbbcc", "aabbccd" };
var arStr = new string[] { "a", "b", "c" };
var str = string.Join("", arStr);
var result = from p in arr
let arCharL = arStr.Select(a => Convert.ToChar(a)).ToArray()
let arCharR = p.ToCharArray()
where p.Trim(arCharL).Length == 0 && str.Trim(arCharR).Length == 0
select p;

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

Categories

Resources