append ". " after selected item values of checkbox list - c#

I have a check box list item with List items in it. When i save the form selected values should be save to database .
See my logic.
string Type = null;
for (int i = 0; i < chbCourse.Items.Count; i++)
{
if (chbCourse.Items[i].Selected == true)
{
Type += chbCourse.Items[i].ToString() + ",";
}
}
It is working great but because of the "," which is i am putting between two values they are separated with each other, but at last item also it will append the "," . Is there any way to remove last "," or insert "." at last ","
Is there any logic for doing this?

Join all selected items, using string.Join and LINQ:
Type = string.Join(",",
chbCourse.Items.Cast<ListItem>().Where(x => x.Selected).Select(x => x.Text));
Since string.Join only adds the separator between items, it won't add an extra comma to the end.
(Also, calling ToString() on a ListItem displays the class type; you have to use the Text property.)

void Main()
{
var a="1,2,3,";
a=a.TrimEnd(new [] {','});
Console.WriteLine (a); //1,2,3
}

Do it like this for selected items:
string Type = string.Join(",", CheckBoxList1.Items.Cast<ListItem>().Where(a=>a.Selected).Select(a => a.Text));
if (!string.IsNullOrEmpty(Type)) // To add '.' at end
Type = Type + ".";

The easiest way is to use String.Join:
string Type = String.Join(",", chbCourse.Items);
If "." is also required
string Type = String.Concat(String.Join(",", chbCourse.Items),".");

If I'd wanted to put dot (".") on the last character, then I would do:
for (int i = 0; i < chbCourse.Items.Count; i++)
{
if (chbCourse.Items[i].Selected == true)
{
if (i == chbCourse.Items.Count - 1) Type += chbCourse.Items[i].ToString() + ".";
else
Type += chbCourse.Items[i].ToString() + ",";
}
}

string Type = null;
for (int i = 0; i < chbCourse.Items.Count; i++)
{
if (chbCourse.Items[i].Selected == true)
{
Type += chbCourse.Items[i].ToString() + ",";
}
}
if(Type != null)
Type = Type.TrimEnd(',');
Try not to use Class Names as variable names.

How about
string Type = null;
type = String.Join(",",
chbCourse.Items.Where(Function(x) x => x.Selected)
.Select(Function(y) y => y.ToString()).ToArray);

Related

Convert Array List to Comma Separated String in C#

I'm using String.Join to attempt to turn an array list into a string that is comma separated, such as
xxx#xxx.com,yyy#xxx.com,zzz#xxx.com,www#xxx.com
I can't seem to get the syntax working.
Here's what I'm trying:
for (i = 0; i < xxx; i++)
{
MailingList = arrayList[i].ToString();
MailingList = string.Join(", ", MailingList.ToString());
Response.Write(MailingList.ToString());
}
Can you help me?
Thank you in advance-
Guessing from the name of your variable (arrayList), you've got List<string[]> or an equivalent type there.
The issue here is that you're calling ToString() on the array.
Try this instead:
for (i = 0; i < xxx; i++)
{
var array = arrayList[i];
MailingList = string.Join(", ", array);
Response.Write(MailingList);
}
EDIT: If arrayList is simply an ArrayList containing strings, you can just do
Response.Write(string.Join(", ", arrayList.OfType<string>()));
Personally I would avoid using nongeneric collections (such as ArrayList) if possible and use strongly-typed collections from System.Collections.Generic such as List<string>. For example, if you have a piece of code that depends on that all contents of the ArrayList are strings, it will suffer catastrophically if you accidentally add an item that's not a string.
EDIT 2: If your ArrayList actually contains System.Web.UI.WebControls.ListItems like you mentioned in your comment: arrayList.AddRange(ListBox.Items);, then you'll need to use this instead:
Response.Write(string.Join(", ", arrayList.OfType<ListItem>()));
The second parameter for String.Join needs to be an IEnumerable. Replace MailingList.ToString() with arrayList and it should work.
Initialization:
string result = string.Empty;
For value types:
if (arrayList != null) {
foreach(var entry in arrayList){
result += entry + ',';
}
}
For reference types:
if (arrayList != null) {
foreach(var entry in arrayList){
if(entry != null)
result += entry + ',';
}
}
And cleanup:
if(result == string.Empty)
result = null;
else
result = result.Substring(0, result.Length - 1);
most of the answers are already there, still posting a complete - working snippet
string[] emailListOne = { "xxx#xxx.com", "yyy#xxx.com", "zzz#xxx.com", "www#xxx.com" };
string[] emailListTwo = { "xxx#xxx1.com", "yyy#xxx1.com", "zzz#xxx1.com", "www#xxx1.com" };
string[] emailListThree = { "xxx#xxx2.com", "yyy#xxx2.com", "zzz#xxx2.com", "www#xxx.com" };
string[] emailListFour = { "xxx#xxx3.com", "yyy#xxx3.com", "zzz#xxx3.com", "www#xxx3.com" };
List<string[]> emailArrayList = new List<string[]>();
emailArrayList.Add(emailListOne);
emailArrayList.Add(emailListTwo);
emailArrayList.Add(emailListThree);
emailArrayList.Add(emailListFour);
StringBuilder csvList = new StringBuilder();
int i = 0;
foreach (var list in emailArrayList)
{
csvList.Append(string.Join(",", list));
if(i < emailArrayList.Count - 1)
csvList.Append(",");
i++;
}
Response.Write(csvList.ToString());

First or Last element in a List<> in a foreach loop

I have a List<string> and I want to identify either the first or last element in the list so I can identify a different function to do with that item.
Eg.
foreach (string s in List)
{
if (List.CurrentItem == (List.Count - 1))
{
string newString += s;
}
else
{
newString += s + ", ";
}
}
How would I go about defining List.CurrentItem? Would a for loop be better in this situation?
Rather make use of String.Join
Concatenates the elements of a specified array or the members of a
collection, using the specified separator between each element or
member.
It is a lot simpler.
Something like
string s = string.Join(", ", new List<string>
{
"Foo",
"Bar"
});
You can use a linq based solution
Example :
var list = new List<String>();
list.Add("A");
list.Add("B");
list.Add("C");
String first = list.First();
String last = list.Last();
List<String> middle_elements = list.Skip(1).Take(list.Count - 2).ToList();
you can use the counter like this
int counter = 0 ;
foreach (string s in List)
{
if (counter == 0) // this is the first element
{
string newString += s;
}
else if(counter == List.Count() - 1) // last item
{
newString += s + ", ";
}else{
// in between
}
counter++;
}
Try something like this:
string newString = "";
foreach (string s in List)
{
if( newString != "" )
newString += ", " + s;
else
newString += s;
}

How to assign dynamically created objects to a string?

I have a form with this code assigned to a button:
TextBox[] tbxCantServ = new TextBox[1];
int i;
for (i = 0; i < tbxCantServ.Length; i++)
{
tbxCantServ[i] = new TextBox();
}
foreach (TextBox tbxActualCant in tbxCantServ)
{
tbxActualCant.Location = new Point(iHorizontal, iVertical);
tbxActualCant.Visible = true;
tbxActualCant.Width = 44;
tbxActualCant.MaxLength = 4;
this.Controls.Add(tbxActualCant);
iVertical = iVertical + 35;
}
And this code creates textboxes dynamically, one for every "button click", so I can have an "add" button to call it and the user can write a list of things that is not limited.
The question is: How can I assign these "textboxes.Text" to a string? They haven't got a name :S
something like:
string sAllBoxes = tbx1.Text + tbx2.Text + "..." + tbxN.Text;
Thanks!!
If your tbxCantServ is defined as local to a method, then you have to assign a Name to your TextBoxes like:
int counter = 0;
foreach (TextBox tbxActualCant in tbxCantServ)
{
tbxActualCant.Location = new Point(iHorizontal, iVertical);
tbxActualCant.Name = "tbx" + counter++;
tbxActualCant.Visible = true;
tbxActualCant.Width = 44;
tbxActualCant.MaxLength = 4;
this.Controls.Add(tbxActualCant);
iVertical = iVertical + 35;
}
And later in some other method if you want to get the joined text then you can do:
string sAllBoxes = string.Join(",", this.Controls.OfType<TextBox>()
.Where(r => r.Name.StartsWith("tbx"))
.Select(r => r.Text));
But if you have tbxCantServ defined at class level then you can do:
string sAllBoxes = string.Join(",", tbxCantServ
.Where(r=> r != null)
.Select(r => r.Text));
In string.Join, you can replace , with an empty string or any string depending on your requirement.
You can do it in the same way you created them.
Try this:
string sAllBoxes="";
foreach (TextBox tbxActualCant in tbxCantServ)
{
sAllBoxes+=tbxActualCant.Text;
}
OR
Using a StringBuilder:
StringBuilder textBuilder = new StringBuilder();
foreach (TextBox tbxActualCant in tbxCantServ)
{
textBuilder.Append(tbxActualCant.Text);
}
string allText = textBuilder.ToString();
If you have access to your textbox array, you can easily do this:
string sAllBoxes = string.Join(" ", tbxCantServ.Select(x => x.Text));
If you don't then use Control collection of your Form, and give name to your textboxes so you can access them using this.Controls[txtBoxName].
If you just want to concatanate your texts without a separator, you can also use string.Concat method:
string sAllBoxes = string.Concat(tbxCantServ.Select(x => x.Text));

get values from array and add into one string

Object Book has Author which has property Name of type string.
I want to iterate trough all Authors and add it's Name string to the one string (not array) separated by comma, so this string should be at the as
string authorNames = "Author One, Author two, Author three";
string authorNames = string.Empty;
foreach(string item in book.Authors)
{
string fetch = item.Name;
??
}
You can use the string.Join function with LINQ
string authorNames = string.Join(", ", book.Authors.Select(a => a.Name));
You can use
string authors = String.Join(", ", book.Authors.Select(a => a.Name));
LINQ is the way to go in C#, but for explanatory purposes here is how you could code it explicitly:
string authorNames = string.Empty;
for(int i = 0; i < book.Authors.Count(); i++)
{
if(i > 0)
authorNames += ", ";
authorNames += book.Authors[i].Name;
}
You could also loop through them all, and append them to authorNames and add a comma in the end, and when it's done simply trim of the last comma.
string authorNames = string.Empty;
foreach(string author in book.Authors)
{
string authorNames += author.Name + ", ";
}
authorNames.TrimEnd(',');
Using LinQ, there are plenty of ways to merge multiple string into one string.
book.Authors.Select(x => x.Name).Aggregate((x, y) => x + ", " + y);
To anwsers James' comment
[TestMethod]
public void JoinStringsViaAggregate()
{
var mystrings = new[] {"Alpha", "Beta", "Gamma"};
var result = mystrings.Aggregate((x, y) => x + ", " + y);
Assert.AreEqual("Alpha, Beta, Gamma", result);
}

How to remove comma separated value from a string?

I want to remove a comma separated value from the string..
suppose I have a string like this
string x="r, v, l, m"
and i want to remove r from the above string, and reform the string like this
string x="v, l, m"
from the above string i want to remove any value that my logic throw and reform the string.
it should remove the value and comma next to it and reform the string...
The below is specific to my code..
I want to remove any value that I get from the logic, I want to remove it and comma next to it and reform the string with no empty space on the deleted item.. How can I achieve this?
offIdColl = my_Order.CustomOfferAppliedonOrder.TrimEnd(',');
if (offIdColl.Split(',').Contains(OfferID.ToString()))
{
// here i want to perform that operation.
}
Tombala, i applied it like this but it doesn't work..it returns true
if (!string.IsNullOrEmpty(my_Order.CustomOfferAppliedonOrder))
{
offIdColl = my_Order.CustomOfferAppliedonOrder.TrimEnd(',');
if (offIdColl.Split(',').Contains(OfferID.ToString()))
{
string x = string.Join(",", offIdColl.Split(new char[] { ',' },
StringSplitOptions.RemoveEmptyEntries).ToList().Remove(OfferID.ToString()));
}
}
}
Just do something like:
List<String> Items = x.Split(",").Select(i => i.Trim()).Where(i => i != string.Empty).ToList(); //Split them all and remove spaces
Items.Remove("v"); //or whichever you want
string NewX = String.Join(", ", Items.ToArray());
Something like this?
string input = "r,v,l,m";
string output = String.Join(",", input.Split(',').Where(YourLogic));
bool YourLogic(string x)
{
return true;
}
var l = x.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
l.Remove(OfferID.ToString());
x = string.Join(",", l);
Edit: Sorry, you're right. Remove doesn't return the original list. You need multiple statements. But you don't need to trim the end "," implicitly. You can remove that statement from your code as well as the check to see if the item is there or not. The Remove will take it out if it was found or simply return false if it was not found. You don't have to check existence. So remove the TrimEnd from the first and get rid of the second line below:
offIdColl = my_Order.CustomOfferAppliedonOrder; //.TrimEnd(',');
//if (offIdColl.Split(',').Contains(OfferID.ToString()))
Not quite sure if this is what you mean, but this seems simplest and most readable:
string x = "r, v, l, m";
string valueToRemove = "r";
var result = string.Join(", ", from v in x.Split(',')
where v.Trim() != valueToRemove
select v);
Edit: like Bob Sammers pointed out, this only works in .NET 4 and up.
String input = "r, v, l, m, ";
string itemToReplace = "v, ";
string output = input.Replace(itemToReplace, string.Empty)
public void string Remove(string allStuff, string whatToRemove)
{
StringBuilder returnString = new StringBuilder();
string[] arr = allStuff.Split('');
foreach (var item in arr){
if(!item.Equals(whatToRemove)){
returnString.Append(item);
returnString.Append(", ");
}
}
return returnString.ToString();
}
So you want to delete an item (or replace it with a nother value) and join the string again with comma without space?
string x = "r, v, l, m,";
string value = "v";
string[] allVals = x.TrimEnd(',').Split(new []{','}, StringSplitOptions.RemoveEmptyEntries);
// remove all values:
x = string.Join(",", allVals.Where(v => v.Trim() != value));
// or replace these values
x = string.Join(",", allVals.Select(v => v.Trim() == value ? "new value" : v));
// If you want to remove ALL occurences of the item, say "a" you can use
String data = "a, b, c, d, a, e, f, q, a";
StringBuilder Sb = new StringBuilder();
foreach (String item in data.Split(',')) {
if (!item.Trim().Equals("a", StringComparison.Ordinal)) {
if (Sb.Length > 0)
Sb.Append(',');
Sb.Append(item);
}
}
data = Sb.ToString();
Its just single line of code in many ways, two of them are below:
string x = "r,v,l,m";
string NewX = String.Join(",", from i in x.Split(',') where i != String.Empty && i != "v" select i);
OR
string NewX = String.Join(",", x.Split(',').Select(i => i.Trim()).Where(i => i != String.Empty && i != "v"));
Not going about this right. Do you need to keep the string? I doubt you do. Just use a list instead. Can you have duplicates? If not:
offIdColl = my_Order.CustomOfferAppliedonOrder.TrimEnd(',').Split(',');
if (offIdColl.Contains(OfferID.ToString()))
{
offIdColl.Remove(OfferID.ToString());
}

Categories