I have a list of objects that implement ToString(). I need to convert the whole list to one string in one line. How can I do that?
Another method that may help out is string.Join(), which takes a set of objects and will join them with any delimiter you want. For instance:
var combined = string.Join(", ", myObjects);
will make a string that is comma/space separated.
Assuming you mean your objects implement ToString, I believe this will do it:
String.Concat( objects.Select(o=>o.ToString()) );
As per dtb note, this should work as well:
String.Concat( objects );
See http://msdn.microsoft.com/en-us/library/dd991828.aspx
Of course, if you don't implement ToString, you can also do things like:
String.Concat( objects.Select(o=>o.FirstName + " " + o.LastName) );
You can use String.Join to concatenate the object list.
string str = String.Join(",", objects);
None of these worked for me. I'm confused, because the docs explicitly say they won't work (require string, not object). But modifying #Adil's original answer (found by looking at the previous revisions), I got a version that works fine:
string.Join( ",", objectList.Select(c=>c.ToString()).ToArray<string>())
EDIT: as per #Chris's comment - I'm using Unity's version of .NET. I used the Microsoft docs as reference, so I'm still confused why this got downvoted, but ... maybe it's a Unity-specific problem that needs this solution.
You can use Linq Enumerable.Select to select a string object and Enumerable.Aggregate into a string.
string StringConcat = ObjectList.Select(x => { return x.StringValue; }).ToList().Aggregate((a,b) => $"{a},{b}");
Example structure:
ObjectList = List<ObjectClass>();
public class ObjectClass {
public string StringValue { get; set; }
}
Related
I want to create a function but I don't know how it would work or how to create it. I want to create a function something similar to below.
I have a string, lets say its this for example:
string myString = "This is my string and it will forever be my string.";
What if I wanted to split this by a space and get each part? which I do...
string[] parts = myString.Split(' ');
Now, I want to get everything but the first 3 words in my string parts, how would I merge each string in parts except the first 3? which will return
string and it will forever be my string.
Something similar to this:
public string getMergedString(string[] parts, int start) // This method would return everything from where you told it to start...
{
}
public string getMergedString(string[] parts, int start) // This method would return everything from where you told it to start...
{
return String.Join(" ", parts.Skip(start));
}
Quick explanation of the code:
string.Join(separator, IEnumerable values)
This joins an IEnumerable object containing strings to one, unified string.
Docs: https://msdn.microsoft.com/en-us/library/system.string.join(v=vs.110).aspx
parts.Skip(int count)
This part of the code skips a given amount of elements, before returning them.
Skip(int count) is an extension method found in the System.Linq namespace.
You need .Net 3.5 or higher in order for you to be able to use this method.
Docs: https://msdn.microsoft.com/en-us/library/bb358985(v=vs.110).aspx
string myString = "This is my string and it will forever be my string.";
string[] words = myString.Split(' ');
var myNewString = string.Join(" ", words.Skip(3));
I have seen questions related to string builder but was not able to find relevant answer.
My question is "Is it wise to use string builder here? if not how to use it wisely here".
This method is going to run 100000 times. In order to save some memory I used stringbuilder here. but the problem is .ToString() method. Anyway I will have to create a string using .ToString() method so why not initialize filename as string rather than StringBuilder.
internal bool isFileExists()
{
StringBuilder fileName = new StringBuilder(AppDomain.CurrentDomain.BaseDirectory + "Registry\\" + postalCode + ".html");
if (System.IO.File.Exists(fileName.ToString()))
{
return true;
}
else
{
return false;
}
}
All libraries method use string as a parameter not string builder why?
I think I got a lot of confusion in my concepts.
Actually you are not using string builder. You first make a string by:
AppDomain.CurrentDomain.BaseDirectory + "Registry\\" + postalCode + ".html"
And then feed it to the string builder.
To use StringBuilder correctly:
StringBuilder fileName = new StringBuilder();
fileName.Append(AppDomain.CurrentDomain.BaseDirectory);
fileName.Append("Registry\\");
fileName.Append(postalCode );
fileName.Append(".html");
If you make liners to make strings you can just make the string by:
string filenamestr = AppDomain.CurrentDomain.BaseDirectory + "Registry\\" + postalCode + ".html";
In this case you are making a filepath, so it is recommended to use:
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Registry\\" , postalCode , ".html");
Given what your code do (check if a file exists), the real bottleneck will not be using a string or a stringbuilder but checking if the file really exists... So I would let the system do the concatenation of string and taking care of performances:
internal bool isFileExists()
{
return System.IO.File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Registry\\" , postalCode , ".html"));
}
You are actually creating 4 strings here.
The first one is AppDomain.CurrentDomain.BaseDirectory + "Registry\\".
The second one is when you add + postalCode to that string.
The third one when you add + ".html".
The fourth one when you call fileName.ToString().
If you want to use StringBuilder, you should do it like this:
StringBuilder fileName = new StringBuilder(AppDomain.CurrentDomain.BaseDirectory);
fileName.Append("Registry\\");
fileName.Append(".html");
As Hans Kesting kindly reminded me, you are not really creating 4 strings. The compiler optimizes it to one call to String.Concat().
You could also use string.Format. It uses StringBuilder internally.
In your case:
var fileName = string.Format("{0}Registry\\{1}.html", AppDomain.CurrentDomain.BaseDirectory, postalCode);
Is String.Format as efficient as StringBuilder
IO operations (even File.Exists) is more time consuming than String creating; you can't avoid File.Exists test that's why, IMHO, the readability is that matters the most:
String formatting
No redundant if
Implementation:
internal bool isFileExists() {
return File.Exists(String.Format("{0}Registry\\{1}.html",
AppDomain.CurrentDomain.BaseDirectory,
postalCode));
}
In your case, it doesn't make sense to create first a StringBuilder and then a string.
Strings are immutable in C#, and when you need to make changes to them (Replace, Append, etc.) another string is created in the string pool.
The allocation of such has a cost, and in case of several different operations this cost add up and it becomes really expensive.
StringBuilder is an object that can internally change, and is much faster (has a smaller cost) for the upsaid operations, hence it's preferable to use it.
The point in which one is better than the others changes according to the scenario, but as a rule of thumb, if you find yourself changing over and over in the same method the same string, it might be a good idea to use a StringBuilder instead.
It looks weird isFileExists() doesn't use postalCode parameter. Is it just an example or piece of a real code?
I suggest you not to use File.Exists() thousands of times. Make a hashtset with file names and look it up instead.
PHP developer here working with c#.
I'm using a technique to remove a block of text from a large string by exploding the string into an array and then shifting the first element out of the array and turning what remains back into a string.
With PHP (an awesome & easy language) it was just
$array = explode('somestring',$string);
array_shift($array);
$newstring = implode(' ', $array);
and I'm done.
I get so mad at c# for not allowing me to create dynamic arrays and for not offering me default functions that can do the same thing as PHP regarding arrays. Instead of dynamic arrays I have to create lists and predefine key structures etc. But I'm new and I'm sure there are still equally graceful ways to do the same with c#.
Will someone show me a clean way to accomplish this goal with c#?
Rephrase of question: How can I remove the first element from an array using c# code.
Here is how far I've gotten, but RemoveAt throws a error while debugging so I don't believe it works:
//scoop-out feed header information
if (entry_start != "")
{
string[] parts = Regex.Split(this_string, #entry_start);
parts.RemoveAt(0);
this_string = String.Join(" ", parts);
}
I get so mad at c# for not allowing me to create dynamic arrays
You may take a look at the List<T> class. Its RemoveAt might be worth checking.
But for your particular scenario you could simply use LINQ and the Skip extension method (don't forget to add using System.Linq; to your file in order to bring it into scope):
if (entry_start != "")
{
string[] parts = Regex.Split(this_string, #entry_start).Skip(1).ToArray();
this_string = String.Join(" ", parts);
}
C# is not designed to be quick and dirty, nor it particularly specializes in text manipulation. Furthermore, the technique you use for removing some portion of a string from a beginning is crazy imho.
Why don't you just use String.Substring(int start, int length) coupled with String.IndexOf("your delimiter")?
Here is the corresponding C# code:
string input = "a,b,c,d,e";
string[] splitvals = input.Split(',');
string output = String.Join(",", splitvals, 1, splitvals.Length-1);
MessageBox.Show(output);
You can use LINQ for this:
if (entry_start != "")
this_string = String.Join(" ", Regex.Split(this_string, #entry_start).Skip(1).ToArray());
string split = ",";
string str = "asd1,asd2,asd3,asd4,asd5";
string[] ary = str.Split(new string[] { split }, StringSplitOptions.RemoveEmptyEntries);
string newstr = string.Join(split, ary, 1, ary.Count() - 1);
splits at ",". removes the first record. then combines back with ","
As stated above, you can use LINQ. Skip(int) will return an IEnumerable<string> that you can then cast back as array.
string[] myArray = new string[]{"this", "is", "an", "array"};
myArray = myArray.Skip(1).toArray();
You might be more comfortable with generic lists than arrays, which work more like PHP arrays.
List<T>
But if your goal is "to remove a block of text from a large string" then the easier way would be:
string Example = "somestring";
string BlockRemoved = Example.Substring(1);
// BlockRemoved = "omestring"
Edit
I misunderstood the question, thinking you were just removing the first element from the array where the array consisted of the characters that make up the string.
To split a string by a delimiter, look at the String.Split method instead. Some good examples are given here.
How do I convert a list to a string in C#?
When I execute toString on a List object, I get:
System.Collections.Generic.List`1[System.String]
Maybe you are trying to do
string combinedString = string.Join( ",", myList.ToArray() );
You can replace "," with what you want to split the elements in the list by.
Edit: As mentioned in the comments you could also do
string combinedString = string.Join( ",", myList);
Reference:
Join<T>(String, IEnumerable<T>)
Concatenates the members of a collection, using the specified separator between each member.
I am going to go with my gut feeling and assume you want to concatenate the result of calling ToString on each element of the list.
var result = string.Join(",", list.ToArray());
You could use string.Join:
List<string> list = new List<string>()
{
"Red",
"Blue",
"Green"
};
string output = string.Join(Environment.NewLine, list.ToArray());
Console.Write(output);
The result would be:
Red
Blue
Green
As an alternative to Environment.NewLine, you can replace it with a string based line-separator of your choosing.
String.Join(" ", myList) or String.Join(" ", myList.ToArray()). The first argument is the separator between the substrings.
var myList = new List<String> { "foo","bar","baz"};
Console.WriteLine(String.Join("-", myList)); // prints "foo-bar-baz"
Depending on your version of .NET you might need to use ToArray() on the list first..
If you want something slightly more complex than a simple join you can use LINQ e.g.
var result = myList.Aggregate((total, part) => total + "(" + part.ToLower() + ")");
Will take ["A", "B", "C"] and produce "(a)(b)(c)"
You have a List<string> - so if you want them concatenated, something like
string s = string.Join("", list);
would work (in .NET 4.0 at least). The first parameter is the delimiter. So you could also comma-delimit etc.
You might also want to look at using StringBuilder to do running concatenations, rather than forming a list.
The .ToString() method for reference types usually resolves back to System.Object.ToString() unless you override it in a derived type (possibly using extension methods for the built-in types). The default behavior for this method is to output the name of the type on which it's called. So what you're seeing is expected behavior.
You could try something like string.Join(", ", myList.ToArray()); to achieve this. It's an extra step, but it could be put in an extension method on System.Collections.Generic.List<T> to make it a bit easier. Something like this:
public static class GenericListExtensions
{
public static string ToString<T>(this IList<T> list)
{
return string.Join(", ", list);
}
}
(Note that this is free-hand and untested code. I don't have a compiler handy at the moment. So you'll want to experiment with it a little.)
It's hard to tell, but perhaps you're looking for something like:
var myString = String.Join(String.Empty, myList.ToArray());
This will implicitly call the ToString() method on each of the items in the list and concatenate them.
This method helped me when trying to retrieve data from Text File and store it in Array then Assign it to a string avariable.
string[] lines = File.ReadAllLines(Environment.CurrentDirectory + "\\Notes.txt");
string marRes = string.Join(Environment.NewLine, lines.ToArray());
Hopefully may help Someone!!!!
If you're looking to turn the items in a list into a big long string, do this: String.Join("", myList). Some older versions of the framework don't allow you to pass an IEnumerable as the second parameter, so you may need to convert your list to an array by calling .ToArray().
The direct answer to your question is String.Join as others have mentioned.
However, if you need some manipulations, you can use Aggregate:
List<string> employees = new List<string>();
employees.Add("e1");
employees.Add("e2");
employees.Add("e3");
string employeesString = "'" + employees.Aggregate((x, y) => x + "','" + y) + "'";
Console.WriteLine(employeesString);
Console.ReadLine();
This seems to work for me.
var combindedString = new string(list.ToArray());
If your list has fields/properties and you want to use a specific value (e.g. FirstName), then you can do this:
string combindedString = string.Join( ",", myList.Select(t=>t.FirstName).ToArray() );
string strs="111,222,333"
string.Join(",",strs.Split(',').ToList().Select(x=>x.PadLeft(6,'0')).ToArray());
The output
000111,000222,000333
string x;
foreach(var item in collection)
{
x += item+",";
}
can I write something like this with lambdas?
Assuming C#, have you tried String.Join()? Or is using lambdas mandatory?
Example:
string[] myStrings = ....;
string result = String.Join(",", myStrings);
EDIT
Although the original title (and example) was about concatenating strings with a separator (to which String.Join() does the best job in my opinion), the original poster seems to ask about the broader solution: how to apply a custom format a list of strings.
My answer to that is write your own method. String.Join has a purpose, reflected by its name (joins some strings). It's high chance that your format logic has a meaning in your project, so write it, give it a proper name and use it.
For instance, if you want to output <li>text</li> for every item, make something as this:
string FormatAsListItems(string[] myStrings)
{
StringBuilder sb = new StringBuilder();
foreach (string myString in myStrings)
{
sb.Append("<li>").Append(myString).Append("</li>");
}
}
I think the intent is clearer, and you also don't take the performance hit of concatenating strings in a loop.
string x = string.Join(",", collection);
You are looking too far for the solution. The String class has a Join method for this:
string x = String.Join(",", collection);
string[] text = new string[] { "asd", "123", "zxc", "456" };
var result = texts.Aggregate((total, str) => total + "," + str);
Shorter syntax, thanks to Earwicker
Does this answer your question?
Most efficient way to concatenate strings?
Note that you can do this with Aggregate, but the built-in string.Join is both easier to use and faster for long arrays.