Convert list to string with single quotes - c#

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() + "'");

Related

Convert List Combo into Comma-Separated String in c#

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)

Adding a custom option to a view bag list

This is the code I have to get a list of certifications. I want to also add the word "All" to the list. How would I do that? When I try + "ALL" at the end of the statement it does not work.
ViewBag.CertificationList = (from r in _context.INT_Certifications select r.Certification).Distinct();
Did you tried something like this? (untested):
var lst = (from r in _context.INT_Certifications select r.Certification).Distinct().ToList();
lst.add("all");
ViewBag.CertificationList = lst;
I want to also add the word "All" to the list
I am going to take you by the word here :) Try this:
List<string> res = (from r in _context.INT_Certifications select r.Certification).Distinct().ToList();
res.Add(" All");
ViewBag.CertificationList = res;
When I try + "ALL" at the end of the statement it does not work.
Because you are trying to concatenate a string to a IEnumerable<string>
IEnumerable<string> does not know the + operator. If you want to have the elements of an enumeration in a string you can tranform it like this:
string allItems = String.Join(" ", ViewBag.CertificationList) + " All";

Extracting field values from IEnumerable

I have a variable results which holds ResultView as shown below:
In turn StoryQ.Execution.Result IEnumerable will hold values:
I need to extract text representation like " Story is Story". How can I achieve this. Could anyone help me on this. Thanks
Solution is to use select in conjunction with string format.
.Select( c => new {Story_Prefix_Text = string.Format("{0} {1}" ,c.Prefix, c.Text)})
or without lambda
from currentpath in collection
select new { Story_Prefix_Text = currentpath.Prefix + " " + currentpath.Text };
Answering my own question just in case it would help somebody in future.
The problem was solved by converting IEnumerable to List and then iterating through foreach loop. Code snippet is below:
var textFormat = ((IStepContainer)v).SelfAndAncestors().Reverse().ToList();
foreach (var text in textFormat)
{
var StoryInText = text.Step.Prefix + " " + text.Step.Text;
}

how to remove the extra AND from the loop

foreach (string word in allTheseWords)
{
allTheseStringsWhereClause = allTheseStringsWhereClause +
" report=" +
word +
" AND ";
}
The problem is after the loop, the SQL clause has an extra AND at the end of it.
How do I fix this?
you can alternatively use LINQ
string _final = string.Join(" AND ", (allTheseWords.Select(x => "report=" + x)));
By inserting user input into a sql where clause you are introducing a vector for a SQL Injection Attack. Do no use this approach. Basically you want to use SQL Parameters.
where report in #allTheseWords
See http://en.wikipedia.org/wiki/SQL_injection
EDIT
See the answer with the most votes in Parameterize an SQL IN clause for how to really do parameterised in query.
This kind of question is very common and here's the proof.
Delete last char of string
How to delete last character in a string in C#?
Finding the last index of an array
But here my simple solution
string[] allTheseWords = { "try", "test", "let" };
string whereLine = string.Empty;
foreach (var item in allTheseWords)
whereLine += "report = " + item.ToString() + " and ";
string final = whereLine.Remove(whereLine.Length - 5);
Console.WriteLine(final);
Console.ReadLine();
A simple way would be to add a bogus always-true clause (and move the AND):
string allTheseStringsWhereClause = "WHERE 1=1";
foreach (string word in allTheseWords)
{
allTheseStringsWhereClause = allTheseStringsWhereClause +
" AND report=" +
word;
}
You don't need LINQ, just use Join:
string whereClause = " report=" + String.Join(" AND report=", allTheseWords);
The best way to do this without hard coding a substring method is to try an Aggregate LINQ query
var result = allTheseWords.Aggregate(allTheseStringsWhereClause, (current, word) => current + " report=" + word + " AND ");
Easy. You just need to do allTheseStringsWhereClause.substr(0,-4) and that's it!

Adding string in front and at end of a list

I have list of names:
IEnumerable<Name> names;
names = n.GetNames(abc);
It gets list like: Ken, John, Sam,... I want it to show like this:
'Ken', 'John', 'Sam',...
I tried this:
string s = string.Join("',", names); but it gives result like:
Ken', John', Sam',...
Is there a way to add "'" in front of these names in single line of code?
Try this.
string s = string.Join(",", names.Select(s => string.Format("'{0}'", s)).ToArray());
I think you were almost there:
string s = "'" + string.Join("','", names) + "'";

Categories

Resources