Sorry for the dumb question, but I am having a bit of trouble with this. I would like to return
"James, Sam, Amanda"
but I am getting
"{ nameA = James, nameB = Sam, NameC = Amanda },"
Little help for a slow guy?
string str = String.Join(",", lst.Select(s => new { s.nameA, s.nameB, s.nameC }));
String.Join concatenates all the elements of a string array, using the delimiter you provide.
So, just send your list to an array:
string str = String.Join(",",lst.ToArray());
Also:
string str = String.Join(",", new[] { s.nameA, s.nameB, s.nameC });
Assuming that you have a list of string
you can do
string str = String.Join(",",lst.ToArray());
if lst contains your names, you just need
string str = String.Join(", ", lst.ToArray());
Just use the string.Format instead of.
string result = string.Format("{0},{1},{2}", lst.ToArray());
Related
I need help. I tried to split a String, but I did not find the perfect way.
Example:
string data = "Car1#4$doors&1$engine&100$horsepower&2$color"
I want to split this string. The result is also a string and should look like 4 doors, 1 engine, 100 horsepower, 2 color.
Any ideas?
var res = string.Join(", ", data.Substring(data.IndexOf("#") + 1).Replace("$", " ").Split('&'));
Here's the ugliest line I could come up with to answer your question.
Enjoy!
Console.WriteLine(string.Join("\r\n", "Car1#4$doors&1$engine&100$horsepower&2$color".Split('#').Select(s => s.Replace("&", ", ").Replace('$', ' '))));
Here is one implementation, of course you can remove the matching {0}
string data = "Car1#4$doors&1$engine&100$horsepower&2$color";
string[] dataArray = data.Split('#');
string carProperties = dataArray[1].Replace("$", " ").Replace('&', ',');
Console.WriteLine("{0} {1}", dataArray[0], carProperties);
How to solve substring issue. I have tried to code correctly but not working for me.
The file name is bad_filename.xml or good_filename.xml
what i want is to use substring to result "bad" or "good" where _filename.xml should be removed. how to do this?
From: bad_filename.xml or good_filename.xml
to: bad or good
Try this
string s = "bad_filename.xml";
string sub = s.Substring(0, s.IndexOf("_"));
string sub2 = string.Concat((s.TakeWhile(x => x != '_')));
string sub3 = s.Split('_')[0];
I've given three ways pick any one of your choice
Note: Way (1) will throw exception when string doesn't contain _ you need to check index > -1
Try this, as I have mention in Question comment.
var result = filename.Split('_')[0];
var result = filename.Split('_')[0];
Use the Path class to get the file name and string.Split to get the first part:
string fileNameWOE = Path.GetFileNameWithoutExtension("bad_filename.xml");
string firstPart = fileNameWOE.Split('_')[0];
try this
string input = "bad_filename.xml"
string sub = input.Substring(0, input.IndexOf("_"));
Console.WriteLine("Substring: {0}", sub);
You can use this code for substring.
string a="bad_filename.xml ";
int index=a.IndexOf('_');
if (index != -1)
{
string filename = a.Substring(0,index);
}
output is bad
do it like this :
string[] strArr = stringFileName.Split('_');
string[] strArr = bad_filename.xml.Split('_');
strArr[0] is "bad"
and
string[] strArr = good_filename.xml.Split('_');
strArr[0] is "good"
I cannot believe I am having trouble with this following string
String filter = "name=Default;pattern=%%;start=Last;end=Now";
This is a short and possibly duplicate question, but how would I split this string to get:
string Name = "Default";
string Pattern = "%%" ;
string start = "Last" ;
string end = "Now" ;
Reason why I ask is my deadline is very soon, and this is literally the last thing I must do. I'm Panicking, and I'm stuck on this basic command. I tried:
pattern = filter.Split(new string[] { "pattern=", ";" },
StringSplitOptions.RemoveEmptyEntries)[1]; //Gets the pattern
startDate = filter.Split(new string[] { "start=", ";" },
StringSplitOptions.RemoveEmptyEntries)[1]; //Gets the start date
I happen to get the pattern which I needed, but as soon as I try to split start, I get the value as "Pattern=%%"
What can I do?
Forgot to mention
The list in this string which needs splitting may not be in any particular order . this is a single sample of a string which will be read out of a stringCollection (reading these filters from Properties.Settings.Filters
Using string.Split this is a two stage process.
In the first case split on ; to get an array of keyword and value pairs:
string[] values = filter.Split(';');
Then loop over the resultant list splitting on = to get the keywords and values:
foreach (string value in values)
{
string[] pair = value.Split('=');
string key = pair[0];
string val = pair[1];
}
String filter = "name=Default;pattern=%%;start=Last;end=Now";
string[] temp = filter.Split('=');
string name = temp[1].Split(';')[0];
string pattern = temp[2].Split(';')[0];
string start = temp[3].Split(';')[0];
string end = temp[4].Split(';')[0];
This should do the trick:
string filter = "name=Default;pattern=%%;start=Last;end=Now";
// Make a dictionary.
var lookup = filter
.Split(';')
.Select(keyValuePair => keyValuePair.Split('='))
.ToDictionary(parts => parts[0], parts => parts[1]);
// Get values out of the dictionary.
string name = lookup["name"];
string pattern = lookup["pattern"];
string start = lookup["start"];
string end = lookup["end"];
The start date ends up at the thrird position in the array:
startDate = filter.Split(new string[] { "start=", ";" }, StringSplitOptions.RemoveEmptyEntries)[2];
Instead of splitting the string once for each value, you might want to split it into the separate key-value pairs, then split each pair:
string[] pairs = filter.Split(';');
string[] values = pairs.Select(pair => pair.Split('=')[1]).ToArray();
string name = values[0];
string pattern = values[1];
string start = values[2];
string end = values[3];
(This code of course assumes that the key-value pairs always come in the same order.)
You could also split the string into intersperced array, so that every other item is a key or a value:
string[] values = filter.Split(new string[] { "=", ";" }, StringSplitOptions.None);
string name = values[1];
string pattern = values[3];
string start = values[5];
string end = values[7];
Edit:
To handle key-values in any order, make a lookup from the string, and pick values from it:
ILookup<string, string> values =
filter.Split(';')
.Select(s => s.Split('='))
.ToLookup(p => p[0], p => p[1]);
string name = values["name"].Single();
string pattern = values["pattern"].Single();
string start = values["start"].Single();
string end = values["end"].Single();
You can use SingleOrDefault if you want to support values being missing from the string:
string name = values["name"].SingleOrDefault() ?? "DefaultName";
The lookup also supports duplicate key-value pairs. If there might be duplicates, just loop through the values:
foreach (var string name in values["name"]) {
// do something with the name
}
Well I tried something like this:
var result = "name=Default;pattern=%%;start=Last;end=Now".Split(new char[]{'=',';'});
for(int i=0;i<result.Length; i++)
{
if(i%2 == 0) continue;
Console.WriteLine(result[i]);
}
and the output is:
Default
%%
Last
Now
Is this what you want?
You see, the thing is now that your Split on filter a second time still starts from the beginning of the string, and it matches against ;, so since the string hasn't changed, you still retrieve previous matches (so your index accessor is off by X).
You could break this down into it's problem parts, such that:
var keyValues = filter.Split(';');
var name = keyValues[0].Split('=')[1];
var pattern = keyValues[1].Split('=')[1];
var start = keyValues[2].Split('=')[1];
var end = keyValues[3].Split('=')[1];
Note that the above code is potentially prone to error, and as such should be properly altered.
You can use the following:
String filter = "name=Default;pattern=%%;start=Last;end=Now";
string[] parts = filter.Split(';');
string Name = parts[0].Substring(parts[0].IndexOf('=') + 1);
string Pattern = parts[1].Substring(parts[1].IndexOf('=') + 1);
string start = parts[2].Substring(parts[2].IndexOf('=') + 1);
string end = parts[3].Substring(parts[3].IndexOf('=') + 1);
Use this:
String filter = "name=Default;pattern=%%;start=Last;end=Now";
var parts = filter.Split(';').Select(x => x.Split('='))
.Where(x => x.Length == 2)
.Select(x => new {key = x[0], value=x[1]});
string name = "";
string pattern = "";
string start = "";
string end = "";
foreach(var part in parts)
{
switch(part.key)
{
case "name":
name = part.value;
break;
case "pattern":
pattern = part.value;
break;
case "start":
start = part.value;
break;
case "end":
end = part.value;
break;
}
}
If you don't need the values in named variables, you only need the second line. It returns an enumerable with key/value pairs.
My solution has the added benefits that the order of those key/value pairs in the string is irrelevant and it silently ignores invalid parts instead of crashing.
I found a simple solution on my own too. Most of your answers would have worked if the list would have been in the same order every single time, but it wont be. the format however, will always stay the same. The solution is a simple iteration using a foreach loop, and then checking if it starts with a certain word, namely, the word I am looking for, like Name, Pattern etc.
Probably not the most cpu efficient way of doing it, but it is C# for dummies level. Really brain-fade level.
Here is my beauty.
foreach (string subfilter in filter.Split(';')) //filter.Split is a string [] which can be iterated through
{
if (subfilter.ToUpper().StartsWith("PATTERN"))
{
pattern = subfilter.Split('=')[1];
}
if (subfilter.ToUpper().StartsWith("START"))
{
startDate = subfilter.Split('=')[1];
}
if (subfilter.ToUpper().StartsWith("END"))
{
endDate = subfilter.Split('=')[1];
}
}
I have a string like "3.9" I want to convert this string in to a number without using split function.
If string is 3.9 => o/p 39
If string is 1.2.3 => o/p 123
I'm not sure what the purpose is. Would it work for your case to just remove the periods and parse the number?
int result = Int32.Parse(str.Replace(".", String.Empty));
You could remove replace the . with empty string before trying to parse it:
string inputString = "1.2.3";
int number = int.Parse(inputString.Replace(".", ""));
string str = "3.9";
str = str.Replace(".","");
int i;
int.TryParse(str, out i);
I would probably go with something like this:
string str = "3.2";
str = str.Replace(".", "");
double number = convert.ToDouble(str);
you can use Replace(".",""); for this purpose
eg:
string stnumber= "5.9.2.5";
int number = Convert.ToInt32(stnumber.Replace(".", ""));
i think Convert.ToInt32(); is better than int.Parse();
Is there an easy way to convert a string array into a concatenated string?
For example, I have a string array:
new string[]{"Apples", "Bananas", "Cherries"};
And I want to get a single string:
"Apples,Bananas,Cherries"
Or "Apples&Bananas&Cherries" or "Apples\Bananas\Cherries"
A simple one...
string[] theArray = new string[]{"Apples", "Bananas", "Cherries"};
string s = string.Join(",",theArray);
The obvious choise is of course the String.Join method.
Here's a LINQy alternative:
string.Concat(fruit.Select((s, i) => (i == 0 ? "" : ",") + s).ToArray())
(Not really useful as it stands as it does the same as the Join method, but maybe for expanding where the method can't go, like alternating separators...)
String.Join Method (String, String[])
You can use Aggregate, it applies an accumulator function over a sequence.
string[] test = new string[]{"Apples", "Bananas", "Cherries"};
char delemeter = ',';
string joinedString = test.Aggregate((prev, current) => prev + delemeter + current);