Place contents of IList into a label? - c#

I'm trying to find a way to print the results of an IList into a label so I can see what exactly is being returned. I need to check the info stored in the IList in order to see if anything is amiss.
IList<OrderItem> orderItems
If I wanted to put the contents of orderItems into a label, how would I do that? Do I need String.Join? Do I need a foreach?

I would suggest building an IEnumerable<string> from your order items, then turn that into a single string via String.Join:
// This formats each item as ID:Name
var itemsAsText = orderItems.Select(item => string.Format("{0}:{1}", item.ID, item.Name));
label.Text = string.Join(", ", itemsAsText);

List<OrderItem> tmp = orderedItems as List<OrderItem>;
tmp.ForEach(a => this.Label1.Text += a.PropertyHere.ToString());

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.

c# listbox multiselect, selectedItems winforms

I saw many examples of getting the values from selectedItems, but in my case I would like to somehow separate these values. What I mean is, for example if I have in my list options like work home forrest car, I would like to be able after choosing work and home to get both text separated and save them in some string variable.
Now I am doing it this way:
string text = "";
foreach (var item in customListBox1.SelectedItems)
{
text += item.ToString() + " ";
}
Later I am filtering datagridview based on this selecteditems in such way:
var result = list3.Where(Srodek => Srodek.Srodek.category1 == text);
That is why I need them separated. How can I do it?
If something is not clear, please let me know, I will try to explain it more.
You can do something better like this:
string text = string.Join(",", customListBox1.SelectedItems.OfType<Object>().Select(x => x.ToString()).ToArray());
var list = customListBox1.SelectedItems.Cast<string>().ToList();
var result = list3.Where(Srodek => list.Any(x=>x == Srodek.Srodek.category1));

Returning list of list values (consolidated)

I want to be able to return a list of all "list values" coming from the query.. 'query' below returns multiple rows of results back from db, each as an item in a list. A sample result back from db would look like...
sample query results when I put break point: (this is what first line of code below 'query' returns from db)
Name = John ; Address = 1230, Ewded ; listOfCities = "NY, CH, LA"
Name = Eric; Address = 12 , Ewded ; listOfCities = "BO, SE, OR"
Code:
List<Index.Result> query = getresultsbackfromdb();
// query content at this point looks like above 1,2
List<string> result = new List<string>();
foreach (var item in query)
{
results.Add(item.listCities);
//'results' list takes in string and not a list
//How do I return a consolidated list of items
}
return result; // this should have ""NY, CH, LA, BO, SE, OR"
//I am trying to get a list of all cities from 1,2 included in
//one single list.
There is method in a List that allows you to add multiple items
foreach (var item in query)
{
results.AddRange(item.listCities);
}
Docs for List.AddRange Method.
Also, just in case if you need to filter out some repeated items, you can use a Distinct LINQ method.
You can try this code based on Split Method
var result = yourString.Split(',');
var input = "NY, CH, LA";
var result = input.Split(',');
And you can save this value in List<object>
var list = new List<object>();
list.Add(result );
You want the AddRange and string.Split methods
results.AddRange(string.Split(',', item.ListCities));
string.Split will split the string into an array wherever it finds the given character, and add range will add all items in an array to the list.
Try this:
var result = query.SelectMany(x => x.listOfCities.Split(','));
Or use
var result = query.SelectMany(x => x.listOfCities.Split(',')).Distinct();
to get the list without duplicates.
If you like Linq then you could do this one line:
using System.Linq;
List<string> result = query.SelectMany(s => s.listCities).ToList();
(This does essentially the same thing as oleksii's AddRange.)

Getting One Field Into An Array?

The following lines of code grabs a handful of rows from a database, and puts the value Table.Id into a list of integers. I imagine there is a way to condense this code into a single line, but I'm not sure how.
var result db.Table.Where(a=>a.Value>0).ToList();
List<int> ids = new List<int>();
foreach(var row in result){
ids.Add(row.Id);
}
Any help would be appreciated, thanks!
Edit: My title says array, my example has a list, either one is fine. Sorry if there was any confusion.
var ids = db.Table.Where(a => a.Value > 0).Select(row => row.Id).ToList();
Should do the trick unless my fu is off
Try this:
var result = db.Table.Where(a=>a.Value>0)
.Select(a=>a.Id)
.ToList();
You can also use the List.ForEach Method. So something like:
db.Table.Where(a=>a.Value>0).ToList().ForEach(delegate(Table row) { ids.Add(row.Id); });

Create a list of items within 'var response'

I have the following code:
var request = new GeocodingRequest();
request.Address = postcode;
request.Sensor = "false";
var response = GeocodingService.GetResponse(request);
var result = response.Results. ...?
I'd very much like to get result as a list, but I can't seem to convert it. I know I can do something like response.Results.ToList<string>();, but have had no luck.
Can anyone help please :)
Well you can just use:
GeocodingResult[] results = response.Results;
or
List<GeocodingResult> results = response.Results.ToList();
If you want a list of strings, you'll need to decide how you want to convert each result into a string. For example, you might use:
List<string> results = response.Results
.Select(result => result.FormattedAddress)
.ToList();
It is defined as:
[JsonProperty("results")]
public GeocodingResult[] Results { get; set; }
if you want to make it list call: response.Results.ToList().
But why do you want to make it list? You can insert items into list, but I don't think you need it.
assuming response.Results is IEnumerable, just make sure System.Linq is available as a namespace and say response.Results.ToList()

Categories