My code is as below:
List<string> colorList = new List<string>();
....
sCombo = reader["Combo"].ToString();
colorList.Add(sCombo.ToString());
....
foreach (var Combo in colorList)
{
Response.Write(string.Join(",", Combo));
}
Output: D410D430D440D420 instead of D410,D430,D440,D420
What is the most simple way to convert the List<string> into a comma-separated string?
EDIT #01
Your suggestion working, but I need this new output :
'D410','D430','D440','D420'
Because use this string on sql query.
Thank you
I think this would be very handy
var colorList = new List<string>() { "D410", "D430", "D440", "D420" };
string commaSeparated = string.Join(",", colorList);
Console.WriteLine(commaSeparated);
or try solution based on Linq
Console.WriteLine(colorList.Select(s => s + ",").Aggregate((s, q) => s + q).TrimEnd(','));
The output
D410,D430,D440,D420
Edit
string result = string.Join(",", colorList.Select(e => "'" + e + "'"));
Console.WriteLine(result);
will give you
'D410','D430','D440','D420'
Without a foreach:
Response.Write(string.Join(",", colorList));
You need to output like this => 'D410','D430','D440','D420'
So try below,
string result = string.Join(",", colorList.Select(x => $"'{x}'"));
Response.Write(result);
What we did above?
Answer: First we flatten each item in your list with a single quoted ('') surrounding string and then we just pass this newly generated flatten result to join method of string with a comma (,) to get your desired output.
Output: (From Debugger)
Related
I am trying to trim an item called Input (object form .json file) which is inside of a foreach loop.
The code I have at the moment is:
List<string> dhurl = new List<string>();
foreach (JObject item in jArray)
{
dhurl.Add("https://" + (string)item.SelectToken("Input");
}
input adds "sm-tiktoktrends.com", I want it to only add "tiktoktrends.com", how can I use trim to remove "sm-"?
*To clarify all Input objects will need sm- removed
The question is not clear if all values start with "sm-". If so, and you're willing to use LINQ:
List<string> dhurl = jArray.Select(item => "https://" + ((string)item.SelectToken("Input")).Substring(3)).ToList();
Otherwise, I might do it something like this:
List<string> dhurl = jArray
.Select(item => (string)item.SelectToken("Input"))
.Select(item => "https://" + (item.StartsWith("sm-") ? item.Substring(3) : item))
.LoList();
New example based on comment below:
List<string> dhurl = jArray
.Select(item =>
string.Format(
"https://{0}/?sig={1}",
((string)item.SelectToken("Input")).Substring(3),
(string)item.SelectToken("Signature")
))
.LoList();
You, probably, should use Substring(...) together with StartsWith(...) instead of Trim(...):
string input = item.SelectToken("Input").ToString();
if (input.StartsWith("sm-"))
{
input = input.Substring(3);
}
dhurl.Add("https://" + input);
dhurl.Add($"https://{item.SelectToken("Input").Replace("sm-","")}") ?
I am trying to create a string from List
This is my code
List<string> SelectedSalesmen = new List<string>();
and I am adding selected salesmen from listBox like this
foreach (ListItem lst in lstBoxSalesmen.Items)
{
if (lst.Selected)
{
SelectedSalesmen.Add(lst.Value);
}
}
finally I am storing that value to a string like this
string SalesManCode = string.Join(",", SelectedSalesmen.ToArray());
But I am getting like this
SLM001,SLM002,SLM003
but I need Output like this
'SLM001','SLM002','SLM003'
Try this:
string SalesManCode = string.Join(",", SelectedSalesmen
.Select(x=>string.Format("'{0}'",x)));
it will wrap all your elements with ' and then join them using , as separator
What about this:
string output = "'" + string.Join("','", SelectedSalesmen) + "'";
Though this'll return '' for an empty input.
Same as the answer from #wudzik but with string interpolation
var salesManCode = string.Join(",", selectedSalesmen.Select(x => $"'{x}'"));
Just use the above one with split like below:
string.Join(",", SelectedSalesmen.Split(',').Select(x => string.Format("'{0}'", x)));
which will give you:
"'SLM001','SLM002','SLM003'"
you can do something like this:
"'" + string.Joing("',", SelectedSalesmen.ToArray() + "'");
How can I extract the substring "John Woo" from the below string in C#
CN=John Woo,OU=IT,OU=HO,DC=ABC,DC=com
Thanks !
You could use a Lookup<TKey, TElement>:
string text = "CN=John Woo,OU=IT,OU=HO,DC=ABC,DC=com";
var keyValues = text.Split(',')
.Select(s => s.Split('='))
.ToLookup(kv => kv[0], kv => kv.Last());
string cn = keyValues["CN"].FirstOrDefault(); // John Woo
// or, if multiple values with the same key are allowed (as suggested in the given string)
string dc = string.Join(",", keyValues["DC"]); // ABC,com
Note that you neither get an exception if the key is not present(as in a dictionary) nor if the key is not uniqe (as in a dictionary). The value is a IEnumerable<TElement>.
Try this
var regex = new Regex("CN=(?<mygroup>.*?),");
var match = regex.Match("CN=John Woo,OU=IT,OU=HO,DC=ABC,DC=com");
if(match.Success)
{
string result = match.Groups["mygroup"].Value;
}
Try this (this is a non generic answer) :
var name = str.Split(',').Where(n => n.StartsWith("CN=")).FirstOrDefault().Substring(3);
Something like this
var s = "CN=John Woo,OU=IT,OU=HO,DC=ABC,DC=com";
// this give you a enumarable of anonymous key/value
var v = s.Split(',')
.Select(x => x.Split('='))
.Select(x => new
{
key = x[0],
value = x[1],
});
var name = v.First().value; // John Woo
You can firstly split the string by the commas to get an array of strings, each of which is a name/value pair separated by =:
string input = "CN=John Woo,OU=IT,OU=HO,DC=ABC,DC=com";
var nameValuePairs = input.Split(new[] {','});
Then you can split the first name/value pair like so:
var nameValuePair = nameValuePairs[0].Split(new[]{'='});
Finally, the value part will be nameValuePair[1]:
var value = nameValuePair[1];
(No error handling shown above - you would of course have to add some.)
I created the below code of my own and finally got the substring I needed. The below code works for every substring that I want to extract that falls after "CN=" and before first occurrence of ",".
string name = "CN=John Woo,OU=IT,OU=HO,DC=ABC,DC=com";
int index1 = name.IndexOf("=") + 1;
int index2 = name.IndexOf(",") - 3;
string managerName = name.Substring(index1, index2);
The Result was "John Woo"
Thanks all for your help...
I have a List strings and each value has a leading quote that needs to be removed. Now there could be quotes further down the string and those will need to stay.
List<string> strings = new List<string>();
strings.Add("'Value1");
strings.Add("'Values2 This 2nd ' should stay");
Is there a linq way?
strings = strings.Select(x => x.StartsWith("'") ? x.Substring(1) : x).ToList();
strings.Select(s => s.StartsWith("'") ? s.Substring(1) : s);
var result = strings.Select(s => s.TrimStart('\''));
Note: This will remove all leading occurrences of ('). However, I assume that you will not have a string like "''Value1".
LINQ is really unnecessary for this. You could just use TrimStart() by itself:
strings.Add("'Value1".TrimStart('\''));
strings.ForEach(s => s = s.TrimStart('\''));
EDIT by Olivier Jacot-Descombes (it demonstrates that this solution does not work):
List<string> strings = new List<string>();
strings.Add("'Value1");
strings.Add("'Values2 This 2nd ' should stay");
Console.WriteLine("Before:");
foreach (string s in strings) {
Console.WriteLine(s);
}
strings.ForEach(s => s = s.TrimStart('\''));
Console.WriteLine();
Console.WriteLine("After:");
foreach (string s in strings) {
Console.WriteLine(s);
}
Console.ReadKey();
This produces the following output on the console:
Before:
'Value1
'Values2 This 2nd ' should stay
After:
'Value1
'Values2 This 2nd ' should stay
I need to read a text file like this
MyItemName = Description # MoreInfo
Now I need to convert this 3 fields in to a table. using the '=' and '#' as pattern.
Just splitting on = and # - this returns and IEnumerable of an anonymous class with the properties you are interested in:
var items = File.ReadAllLines(fileName)
.Skip(1) //Skip header
.Where( line => !string.IsNullOrWhiteSpace(line))
.Select(line =>
{
var columns = line.Split('=', '#');
return new
{
ItemName = columns[0].Trim(),
Description = columns[1].Trim(),
MoreInfo = columns[2].Trim()
};
});
This approach would require the separator tokens to be used as separators exclusively - if they do occur in any of the fields, this will mess up everything and void this approach.
if you really want to use linq for it...
It doesn't look very nice and it doesn't create a table, but you get the point:
from line in File.ReadAllLines(filename)
let eqPos = line.IndexOf('=')
let atPos = line.IndexOf('#')
select new {
Name = line.Substring(0, eqPos).Trim(),
Desc = line.Substring(eqPos + 1, atPos - (eqPos + 1)).Trim(),
Info = line.Substring(atPos + 1).Trim()
}