Variable string editing - c#

I have a form on which you can select multiple items to create a code.
Eg. if I clicked on "name", it would add that to the string, then if I clicked "age" it would then add that to the string, but if I unchecked "name", it would remove it from the string.
I have no idea of how to go about this. Can someone help?

Take a List<string> and add/remove items to/from the list. Once you are done, you make a call to string.Join and construct a single string from array.
List<string> items = new List<string>(); // declare globally
private void add(string item)
{
items.Add(item);
}
private void remove(string item)
{
items.Remove(item);
}
private string convertArrayToString(string delimiter, List<string> elements)
{
delimiter = (delimiter == null) ? "" : delimiter;
return string.Join(delimiter, elements.ToArray());
}
Note:
Giving a priority to List<T> over string[] would be a good decision since, here collection would be resize. Have a look at this discussion which can help you on this.

Simply use a List.
List<string> myList = new List<string>();
myList.Add("Somestring");
Then you can use the following methods:
myList.Remove or myList.RemoveAll or myList.RemoveAt and so on.

Why not using List? it allows you to add/remove elements easily?
if you click on name, just add it to the list, when you uncheck the name, remove it from the list,
after that, you can convert your list into a string and use it.
//Add string
var myList = new List<string>();
//After clicking:
myList.add(clickedElement);
//After uncheck
myList.remove(uncheckedElement);
//At the end, just convert your list to string to use it
var myString = string.Join(" ", myList.ToArray());

Related

How to search through combobox with a string containing a wildcat?

I have a combo-box that contains lots of entries like this small extract
1R09ST75057
1R11ST75070
1R15ST75086
1R23ST75090
2R05HS75063
2R05ST75063
3R05ST75086
2R07HS75086
The user now enters some information in the form that result in a string being produced that has a wildcat (unknown) character in it at the second character position
3?05ST75086
I now want to take this string and search\filter through the combo-box list and be left with this item as selected or a small set of strings.
If I know the string without the wildcat I can use the following to select it in the Combo-box.
cmbobx_axrs75.SelectedIndex = cmbobx_axrs75.Items.IndexOf("2R05HS75063");
I thought I could first create a small subset that all have the first char the same then make a substring of each minus the first two chars and check this but I can have a large amount of entries and this will take too much time there must be an easier way?
Any ideas how I can do this with the wildcat in the string please?
Added info:
I want to end up with the selected item in the Combobox matching my string.
I choose from items on the form and result in string 3?05ST75086. I now want to take this and search to find which one it is and select it. So from list below
1R05ST75086
2R05ST75086
3R05ST75086
6R05ST75086
3R05GT75086
3R05ST75186
I would end up with selected item in Combo-box as
3R05ST75086
You could use regular expressions. Something like this:
string[] data = new string[]
{
"1R09ST75057",
"1R11ST75070",
"1R15ST75086",
"1R23ST75090",
"2R05HS75063",
"2R05ST75063",
"3R05ST75086",
"2R07HS75086"
};
string pattern = "3*05ST75086";
string[] results = data
.Where(x => System.Text.RegularExpressions.Regex.IsMatch(x, pattern))
.ToArray();
You can use a regular expression for this task. First, you need a method to convert your pattern string to Regex like this (it should handle "*" and "?" wildcards):
private static string ConvertWildCardToRegex(string value)
{
return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$";
}
Then you will use it like the following:
List<string> comboBoxValues = new List<string>()
{
"1R09ST75057",
"1R11ST75070",
"1R15ST75086",
"1R23ST75090",
"2R05HS75063",
"2R05ST75063",
"3R05ST75086",
"2R07HS75086"
};
string searchPattern = "3?05ST75086";
string patternAsRegex = ConvertWildCardToRegex(searchPattern);
var selected = comboBoxValues.FirstOrDefault(c => Regex.IsMatch(c, patternAsRegex));
if (selected != null)
{
int selectedIndex = comboBoxValues.IndexOf(selected);
}
This assumes you only care about first found match. If you need all matches then substitute FirstOrDefault(...) with Where(...) clause and swap "if" statement with a foreach loop.
Thanks to all that helped I used a combination of items from all answers so everyone helped me answer this.
I added this function from the answers as it seems a good idea, thanks
private static string ConvertWildCardToRegex(string value)
{
return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$";
}
Then I get the combo box items into a list. I search the list and make some more decisions based on the result of the search.
List<string> comboBoxValues = new List<string>();
for (int i = 0; i < cmbobx_in_focus.Items.Count; i++)
{
comboBoxValues.Add(cmbobx_in_focus.GetItemText(cmbobx_in_focus.Items[i]));
}
string[] results = comboBoxValues
.Where(x => Regex.IsMatch(x, ConvertWildCardToRegex(lbl_raster_used.Text)))
.ToArray();
I now have array called results which is easy to work with.

Append clipboard text to a listbox

So I created a variable to hold my clipboard text and I have no idea on how to append it to a listbox.
This is as far as I got..
private void clipboardBtn_Click(object sender, EventArgs e)
{
string items = Clipboard.GetText();
List<string> _items = new List<string>();
_items.AddRange(items);
}
but that throws me this error..
Argument 1: cannot convert from 'string' to
'System.Collections.Generic.IEnumerable'
What's causing this and how do I fix it? Is this even the correct way of appending text to the listbox?
-UPDATE-
I got this now but everytime I click the button it overwrites the old one instead of appending a new item to the listbox
string items = Clipboard.GetText();
List<string> _items = new List<string>();
_items.Add(items);
listBox1.DataSource =_items;
How do i append a new item?
Clipboard.GetText has the signature
public static string GetText()
but List<T>.AddRange has the signature
public void AddRange( IEnumerable<T> collection )
So essentially you're trying to add a string as an IEnumerable<T> which gives you the above error.
Better use List<T>.Add for that purpose like that:
_items.Add(items);
your question is about List object and not about ListBox control.
the AddRange() method requires a collection, you can transform your string to a collection (Array) by using Split.
private void clipboardBtn_Click(object sender, EventArgs e)
{
string YourGetClipBoardTextString = "aaa;bbb;ccc;ddd";
List<string> _items = new List<string>();
_items.AddRange(YourGetClipBoardTextString.Split(';').ToArray()); // you can split the string by any char seperator ";" " ", "," etc...
}
if you dont need to split the string just use the Add() method:
_items.Add(YourGetClipBoardTextString);
After your update, you can append new items to a listbox in that manner:
foreach (string itm in _items)
{
listBox1.Items.Add(itm);
}
since you're creating new "_items" on every click, you cannot see the old items. try like this,
List<string> _items = new List<string>();
private void clipboardBtn_Click(object sender, EventArgs e)
{
string items = Clipboard.GetText();
_items.Add(items);
listBox1.DataSource =_items;
}
_items declared outside of method scope.
Your problem is that you are initializing a new list each time:
string items = Clipboard.GetText();
List<string> _items = new List<string>();//<New list here results in removal of existing item
_items.Add(items);
listBox1.DataSource =_items;
Try something like this:
string items = Clipboard.GetText();
List<string> _items = listBox1.DataSource as List<string>;// You may have type casting issues here -
_items.Add(items);
listBox1.DataSource =_items;
First you need to split the clipboard contents into strings for each line, then you need to add them to the list box:
string[] items = Clipboard.GetText().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
listBox1.Items.AddRange(items);
If you don't want to have a separate listBox item for each line, just do this:
listBox1.Items.Add(Clipboard.GetText());

Convert string list to string when only item present

I have a function that returns a list of strings:
string displayText;
List<string> list = new List<string>();
list = GetListOfStrings();
if(list.Count > 1)
{
displayText = string.Join("\r", list.ToArray());
}
else
{
displayText = list.ToString();
}
If there are several string in the List then I separate them by \r for display purposes, if there is only one then I cant to convert it to string.
But the above shows "System.Collections.Generic.List1[System.String]" when there is only one string.
What is the best way to do this when there is only one string in the list?
No reason to use ToString on the list -- just grab the first (and only) item:
displayText = list[0];
Both answers in the comments seem correct as well, though ToString on a string is a bit redundant. I think "remove the if" is actually the best answer.
Use SingleOrDefault() for getting the only item in the list
if(list.Count > 1)
{
displayText = string.Join("\r", list.ToArray());
}
else
{
displayText = list.SingleOrDefault();
}
Not having more than one item doesn't mean it has one item.
You can use:
string displayText;
List<string> list = new List<string>();
list = GetListOfStrings();
displayText = string.Join("\r", list);

Add contents of arraylist to string array

In for each loop i am adding the contents into ArrayList. Now i need to add (or copy/move) the contents of arraylist into string array.
By string array i mean string[].
let me know if more info required.
thanks!
Use ToArray:
string[] array = (string[])list.ToArray(typeof(string));
I would recommend you use List<string> though, as that's more type safe:
List<string> list = ...
string[] array = list.ToArray();
Use the toArray() method:
ArrayList alist = ...;
String []strArray = new String[alist.size()];
alist.toArray(strArray);
You can use ToArray, which others have posted, but if you want to do some checking on the original list, or modify specific items as they're entered, you can also use something like this:
var myStringArray = new string[ArrayList.Count];
int i = 0;
foreach(var item in ArrayList)
{
myStringArray[i] = item;
i++;
}

C# Listing/Checking Object Variables?

With an ASP.NET MVC project I'm working on, I am required to check whether bit variables within a LINQ-To-SQL class are true. So far, After checking whether or not each variable is true or false, I then push the value of the field into a List and return it like so:
public List<String> GetVarList() {
List<String> list = new List<String>();
if (fields.SearchBar) {
list.Add("SearchBar");
}
if (fields.SomeField) {
list.Add("SomeField");
}
return list;
}
This, to me, doesn't seem to be the fastest or easiest way to do it.
I was wondering its possible to somehow be able check the value of the variable dynamically from an array of strings by looping through them with either a for or a foreach loop. For instance:
public List<String> GetVarList() {
String[] array = {"SearchBar", "SomeField"};
List<String> list = new List<String>();
foreach (String field in array) {
// Check whether or not the value is true dynamically through the array
}
return list;
}
Thanks for any suggestions!
Certainly, you can use reflection for something like this:
private bool ValueWasSet(string propertyName)
{
var property = fields.GetType().GetProperty(propertyName);
return (bool)property.GetValue(fields, null);
}
public List<string> GetVarList()
{
return new [] {"SearchBar", "SomeField"}
.Where(ValueWasSet)
.ToList();
}
It is a very straight-forward solution to what you want to do, assuming you have a lot of items to look through.
CAVEAT: This is NOT faster than your code. Your code is much faster than this... but if you want to do it more dynamically, you have to pay a slight perf price.
You can use reflection:
public List<String> GetVarList() {
String[] array = {"SearchBar", "SomeField"};
List<String> list = new List<String>();
var type=fields.GetType();
foreach (String field in array) {
var prop=type.GetProperty(field);
if ((bool)prop.GetValue(fields,null))
list.Add(field);
}
return list;
}
From your question is not clear if SearchBar, SomeFields etc. are fields or properties. If they are fields, change the code accordingly (use GetField() instead of GetProperty())

Categories