Formatting List into string - c#

So im running a little issue with my code, how can I convert my List into a normal string with this format
listitem1, listitem2, listitem3
Note that last listitem3 does not have a , at the end.
I tried String.Inser but I cant get the last index..

Sound like you need string.Join
var result = string.Join(", ", yourList);

Use a join which will concatenate your array with a delimiter which you define.
Likewise use a split to turn your delimited spring into an array.
var list = new List<string> {"one", "two", "three"};
var stringList = string.Join(", ", list);
the result will be
one, two, three
If you want the space make sure to include it in the delimeter ", "

Or you can use a foreach loop, to get last item then based on that append a comma :
List<string> mylist = new List<string>();
mylist.Add("Test1");
mylist.Add("Test2");
mylist.Add("Test3");
string lastItem = mylist[mylist.Count - 1];
foreach(string s in mylist)
{
if (s != lastItem)
Console.Write(s + ", ");
else
Console.Write(s);
}
and the result is:
Test1, Test2, Test3

Related

how to get before and after text in the string which contains 'Or' in it

I want a code that takes a string with 'Or' in it and takes text before and after 'Or' and stores it in seperate variable
I tried the substring function
var text = "Actor or Actress";
var result= text.Substring(0, text.LastIndexOf("or"));
but with this getting only actor I want actor as well as actress but in seperate variables as a whole word so it can be anything in place of 'actor or actress'
You need to use one of the flavors of String.Split that accepts an array of string delimiters:
string text = "Actor or Actress";
string[] delim = new string[] { " or " }; // add spaces around to avoid spliting `Actor` due to the `or` in the end
string[] elements = text.Split(delim, StringSplitOptions.None);
foreach (string elem in elements)
{
Console.WriteLine(elem);
}
Output:
Actor
Actress
Note: I am using .NET framework 4.8, but .NET 6 also has an overload of String.Split that accepts a single string delimiter so there's no need to create delim as an array of strings, unless you want to be able to split based on variations like " Or "," or ".
Spli() should do the job
text.Split(β€œor”);
use the Split() method
var text = "Actor or Actress";
Console.WriteLine(text.Split("or")[0]);
Console.WriteLine(text.Split("or")[1]);
Output
Actor
Actress
try this
string[] array = text.Split(' ');
foreach (string item in array)
{
if (item != "or")
{
Console.WriteLine(item);
}
}
Output
Actor
Actress

Compare two strings to find any duplicates

I really cannot find the answer to this question and it is driving me mental. I have two strings, one is a text file that is read into a string called logfile. The other is just a user input string, called text1. Eventually it's just going to be a guessing game with hints, but I can't figure out how to compare these two for equality.
string LOG_PATH = "E:\\Users\\start.txt";
string logfile = File.ReadAllText(LOG_PATH);
string text1 = "";
text1 = Console.ReadLine();
if (logfile.Contains(text1))
{
Console.WriteLine("found");
}
else
{
Console.WriteLine("not found");
}
This code works fine when there is only one word in the text file and matches. If the text file only contains the word "Mostly" and the user entered mostly and a bunch of other words, the console prints found. But if the text file has mostly and a bunch of other random words, say "Mostly cloudy today", the console prints not found. Is it possible to match to strings for ANY duplicates at all?
You can try it with different ways,
Using Except(),
var wordsFromFile = File.ReadAllText(LOG_PATH).Split(' ').ToList();
var inputWords = Console.ReadLine().Split(' ').ToList();
Console.WriteLine(wordsFromFile.Except(inputWords).Any() ? "Found" : "Not Found");
Similar way using foreach() loop,
var wordsFromFile = File.ReadAllText(LOG_PATH).Split(' ').ToList();
var inputWords = Console.ReadLine();
string result = "Not Found";
foreach(var word in inputWords)
{
if(wordsFromFile.Contains(word))
{
result = "Found";
break
}
}
Console.WriteLine(result);
Very similar to what Prasad did, except we ignore blank lines and use a case-insensitive comparison:
string LOG_PATH = #"E:\Users\start.txt";
List<String> logfileWords = new List<String>();
foreach (String line in File.ReadLines(LOG_PATH))
{
logfileWords.AddRange(line.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
}
Console.Write("Words to search for (separated by spaces): ");
String[] inputs = Console.ReadLine().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine("Inputs:");
foreach(String input in inputs)
{
Console.WriteLine(input + " ==> " + (logfileWords.Any(w => w.Equals(input, StringComparison.InvariantCultureIgnoreCase)) ? "found" : "not found"));
}

Dictionary ContainsKey() Doesn't compare string values

I'm a noobie to C# and don't understand why ContainsKey() won't return true with the values bid_amount and bid_amount.
I have a long string ("key=value, key=value...") that is split on , and then = created into a dictionary. But when I test for a known key in the dict bid_amount it always returns false.
Is there a way to compare values using ContainsKey()?
What exactly am I missing?
string[] responseStringSplit = responseString.Split (new []{ ',' });
Dictionary<string,string> responseDict = new Dictionary<string, string> ();
foreach (string word in responseStringSplit)
{
string[] splitString = word.Split (new[]{ ':' });
if (splitString.Length > 1)
{
responseDict.Add(splitString [0],splitString [1]);
}
else
{
Debug.Log ("CouldNotSplit:" + word);
}
}
foreach (KeyValuePair<string, string> entry in responseDict)
{
Debug.Log (entry.Key + "=" + entry.Value);
if (responseDict.ContainsKey ("bid_amount"))
{
Debug.Log ("found bid amount");
}
}
Based on your input, you've got a space between your , and your key. Try calling .Trim() on splitString[0] and splitString[1] before you add it to your dictionary.
responseDict.Add(splitString[0].Trim(), splitString[1].Trim());
If you look carefully at the code and input you have 2 problems:
You first split by "," whereas your input code is "someText, someTextAfterSpace" - So split by ", ".
Then you split by ":" whereas your input code is with "="
Code should be:
//split by ", " (plus the space) to avoid that problem (or use trim)
string[] responseStringSplit = responseString.Split (new []{ ", " });
//split by "=" instead of current ":" (Or change input string from having '=' to ':')
string[] splitString = word.Split (new[]{ '=' });
Besides changing that, adding Trim()s and ToLower() for the key is of course welcome in order to avoid problems with white spaces and uppercase/lowercase

How do I put the contents of a list in a single MessageBox?

Basically, I have a list with multiple items in it and I want a single message box to display them all.
The closest I have got is a message box for each item (using foreach).
What I want is the equivalent of:
MessageBox.Show ("List contains:"+
Foreach (string str in list)
{ str + Environment.Newline + }
)
But obviously this won't work! What is the correct way of doing this?
You can join everything into a single string with string.Join:
var message = string.Join(Environment.NewLine, list);
MessageBox.Show(message);
However, if you don't have access to .NET 4, you don't have that overload that takes an IEnumerable<string>. You will have to fallback on the one that takes an array:
var message = string.Join(Environment.NewLine, list.ToArray());
MessageBox.Show(message);
If you have .Net 4.0
string s = String.Join(",", list);
If you don't but have 3.5
string s = String.Join(",", list.ToArray());
You can also use Stringbuilder:
StringBuilder builder = new StringBuilder();
foreach(string str in list)
{
builder.Append(str.ToString()).AppendLine();
}
Messagebox.Show(builder.ToString());
Regards
Just for fun and in case you need to do something like that with non-string collections one time - a LINQ version using Aggregate, which is the closest to your example syntax. Don't use it here, do indeed use String.Join in this case, but keep in mind that you have something in LINQ that can do what you need.
MessageBox.Show("List contains: " +
list.Aggregate((str,val) => str + Environment.NewLine + val);
EDIT: also, like Martinho Fernandes pointed out, it's better to use the StringBuilder class in cases like that, so:
MessageBox.Show("List contains: " + list.Aggregate(new StringBuilder(),
(sb,val) => sb.AppendLine(val),
sb => sb.ToString()));
simply you need to make a for loop for example:
string total ="";
for(int i =0; i<x.count ;i++)
{
total =total+x[i] +"\n";
}
MessageBox.Show(total);

Generating Comma Separated Values

Suppose I have a collection of strings:
"foo"
"bar"
"xyz"
And I would like to generate a comma separated values from the list into something like:
"foo, bar, xyz"
Notice the lack of ", " at the end.
I am aware that there are dozens of ways to generate this:
use for-loop and string.Format() or StringBuilder.
use integer counter and remove the ending ", " if the value > 0
don't put ", " on the first run
etc.
Sample code of what I have right now:
if (strs.Count() > 0)
{
var sb = new StringBuilder();
foreach (var str in strs)
sb.AppendFormat("{0}, ", str);
return sb.Remove(0, 2).ToString();
}
What is the best code that is highly reusable for the above scenario, and why?
You want to use the string.Join method, which exists in the BCL for this purpose.
Example:
var myArray = new string[] { "one", "two", "three" };
var output = string.Join(", ", myArray);
Or if you're using .NET 3.5, you can do this with any IEnumerable<string> as such:
var output = string.Join(", ", myEnumerable.ToArray());
(Note that this doesn't give the best performance as it requires, although it is clearly still 'O(n)', and should be suitable for almost all cases).
Now, if your enumerable is not of type string (generically an IEnumerable<T>), you can just use the Select method to convert the result into a string, e.g.
var output = string.Join(", ", myEnumerable.Select(e => e.ToString()).ToArray());
I'm not sure if you're dealing with values that may potentially contains commas in themselves, but this can be worked around by enclosing them in quotes (") and escaping the quotes, similarly to the CSV format.
var output = string.Join(", ", items.Select(x => x.Contains(",") ?
"\"" + x.Replace("\"", "\"\"") + "\"" : x);
Of course, splitting them back up again is a slightly triciker task, which requires a bit of regex.
String.Join is the right answer, but in the case of an IEnumerable, Linq is often shorter than a for loop:
someStringCollection.Aggregate((first, second) => first + ", " + second);
As others have said: String.Join is normally the best way to do this. But what if you have just have an IEnumerable rather than an array? Perhaps you have code to enumerate these as you read them from a file using deferred execution. In this case String.Join isn't quite as nice, because you have to loop over the strings twice β€” once to create the array and once to join it. In that case, you want something more like this:
public static string ToDelimitedString(this IEnumerable<string> source, string delimiter)
{
string d = "";
var result = new StringBuilder();
foreach( string s in source)
{
result.Append(d).Append(s);
d = delimiter;
}
return result.ToString();
}
This will perform almost as well as String.Join, and works in the more general case. Then, given a string array or any other IEnumerable you can call it like this:
string finalStr = MyStrings.ToDelimitedString(",");
string finalstr = String.Join(",", strs);
Use
string s = string.Join (",", new string[] {"aaa", "bbb", "ccc"});
Use String.Join
If you have an array of strings, go with Noldorin's solution.
But if it's some other collection type, I might do this:
if (strs.Count() > 0)
{
var sb = new StringBuilder();
foreach (var str in strs)
sb.AppendFormat("{0} {1}", (0 == sb.Length ? "" : ","), str);
return sb.ToString();
}

Categories