C# Converting ListBox to String then Aggregate - c#

I have a listbox being populated from a combo box. What i need to do is string all the contents of the listbox together and then Aggregate it.
string cols = listbox1.items.Aggregate((f, s) => f.value + "," + s.value);
doesnt work.

Items is an ObjectCollection, so all you know for sure is that it contains objects. You can call ToString on any object:
string[] items = listBox1.Items
.OfType<object>()
.Select(item => item.ToString())
.ToArray();
string result = string.Join(",", items);
Note that this is both more readable and more efficient than using aggregate, which causes multiple string concatenations.

pretty old thread, but here's my solution if anybody need it still
string cols = string.Join(",", listBox1.Items.Cast<String>());

Supposing that you have strings in the listbox, try this:
string cols =
String.Join(",", listbox1.Items
.OfType<Object>()
.Select(i => i.ToString())
.ToArray());
Generally String.Join is used to join a string. This is faster than using a StringBuilder as the size of the new string is already known and it doesn't have to copy everything twice.

string cols = listBox1.Items.Cast<string>().Aggregate((f, s) => f + "," + s);

I think you need to explicitly do ToString()
string cols = listbox1.items.Aggregate((f, s) => f.value.ToString() + "," + s.value.ToString());

Related

How to turn array into quote and comma delimited string for sql?

I have a list I want to pass into SQL but they must be single quote and comma delimited.
So List = a b c
But I need a string = 'a','b','c'
How can I accomplish this in a concise manner?
Something like this I think but can't see within LINQ how to add to beginning and end:
String.Join(",", arr.Select(p => p.ToString()).ToArray())
Maybe something along the lines of:
String.Join(",", arr.Select(p=> "'" + p.ToString() + "'").ToArray());
// or is p already a string
String.Join(",", arr.Select(p => "'" + p + "'").ToArray());
You can do this:
String.Join(",", arr.Select(p => $"'{p.ToString()}'").ToArray());
And that will put the ' on either side of p.ToString() for each element.
Use an ORM that supports the following construction:
string[] items = GetItems();
var query = db.Rows.Where(row => items.Contains(row.ColumnName));
This way, you do not open yourself to sql injection by constructing strings to hand to the database yourself.
You should also be careful if your source data contains "'" in which case you need to escape the "'". Try this:
var arr = new [] { "a'c", "b" };
var output = String.Join(",", arr.Select(p => $"'{p.Replace("'", "''")}'"));
That gives "'a''c','b'".

How to concatenate two List<string> to a single string using Aggregate method

I have two lists of strings. My manager's requirement is to concatenate both lists and output as a string using LINQ.
List<string> upper = new List<string> { "A", "B", "C" };
List<string> lower = new List<string> { "a", "b", "c" };
The output should be something as below:
//string output = "A:a,B:b,C:c"
And to achieve this, I need to use LINQ Aggregate method or other extension methods available. Please help
You are looking for the method Zip and maybe combined with string.Join
Console.WriteLine(string.Join(",", upper.Zip(lower, (u, l) => u + ":" + l)));
This outputs: A:a,B:b,C:c
You need Zip method not Aggregate:
If you want the result as a List of String:
List<string> result = upper.Zip(lower, (first, second) => first + ":" + second).ToList();
If you want the result as a string you can either use String.Join method like this:
string output = string.Join(",", result);
Or Aggregate method as you are looking for like this:
string output = result.Aggregate((f, s) => f + "," + s);
Use Enumerable.Zip:
var results = upper.Zip(lower, (up, low) => $"{up}:{low}");
Now to convert it into a single string:
string output = string.Join(",", results);

List<comma-separated strings> => List<string>?

Trying to come up with a LINQy way to do this, but nothing's coming to me.
I have a List<> of objects which include a property which is a comma-separated list of alpha codes:
lst[0].codes = "AA,BB,DD"
lst[1].codes = "AA,DD,EE"
lst[2].codes = "GG,JJ"
I'd like a list of those codes, hopefully in the form of a List of strings:
result = AA,BB,DD,EE,GG,JJ
Thanks for any direction.
Use SelectMany to get all split codes and use Distinct to not repeat the values.
Try something like this:
var result = lst.SelectMany(x => x.codes.Split(",")).Distinct().ToList();
You need to use Split to split each string into multiple strings. Then you need to use SelectMany to concatenate multiple sequences into a single sequence, and then you need to use Distinct to remove duplicates.
var result =
lst
.SelectMany(x => x.codes.Split(','))
.Distinct()
.ToList();
if you need a string as a result:
string result = string.Join(",",lst.SelectMany(p=>p.codes.Split(",")).Distinct());
Try this:
List<string> list = new List<string>();
char[] sep = new char[1];
sep[0] = ',';
foreach (string item in lst)
{
list.AddRange(item.Split(sep));
}
list = list.Distinct().ToList();

Building SQL IN statement from listbox control

I'm trying to build a SQL query using StringBuilder and I've become stuck trying to do part of the WHERE clause.
I have a list box with a bunch of values and allows multiple selection. I need to iterate through the selected items and put then in an IN statement like...
WHERE SOME_FIELD IN ('Value','NextValue','AnotherValue')
so far I've written the code like this...
if (lstSalesGroup.SelectedItem != null)
{
selectQuery.Append("AND SALES_GROUP IN (");
foreach (ListItem item in lstSalesGroup.Items)
{
if (item.Selected)
selectQuery.Append("'" + item.Value + "',");
}
selectQuery.Append(")");
}
I need to test if the item is the last in the loop so that it doesn't put on the "," before the closing ")".
How can I do this? Or if there's a better way to build this part of the query please do suggest, I am still learning, we all have to start somewhere! :)
Eventually this will be a query for a part search.
Thanks in advance
Couple of ways for doing that.
You can use string.TrimEnd to remove the extra comma from the string or you can create a new string using string.Join like
string InPartQuery = string.Join(",", lstSalesGroup.Items
.Cast<ListItem>()
.Where(t => t.Selected)
.Select(r => "'" + r.Value + "'"));
You could use String.Join with some Linq
For clearity I've put the code in variables.
if (lstSalesGroup.SelectedItem != null)
{
var queryStr = "AND SALES_GROUP IN ({0})";
var selectedItemValues = (from itm in lstSalesGroup.Items.Cast<ListItem>()
where itm.Selected
select String.Format("'{0}'", itm));
selectQuery.Append(String.Format(queryStr, String.Join(",", selectedItemValues)));
}
Try using linq
selectQuery.Append("AND SALES_GROUP IN (");
selectQuery.Append(string.Join(",", lstSalesGroup.Items.Select(i => "'" + i.Value + "'")));
selectQuery.Append(")");
This will solve your problem, but you have a problem with SQL injection here. I would strongly advice you to use parameters in your query.
Dim s As String = "'"
For i = 0 To ListBox1.Items.Count - 1
s = s & ListBox1.Items.Item(i) & "','"
Next
Try this:
if (lstSalesGroup.SelectedItem != null)
{
selectQuery.Append("AND SALES_GROUP IN (");
var local = lstSalesGroup.Items.Where(c => c.Selected)
.Select(c => "'"+c.Value+"'")
.Aggregate((c,n) => c+ ", "+n);
selectQuery.Append(local);
selectQuery.Append(")");
}
Look at this example for more info on the .Aggragate(...) method

string.Join throws OutOfMemory Exception

I have a list of strings and I want to join them with " "(space) between them, so I use the string.Join method:
foreach (var line in lines)
{
var strings = lines.Where(l => l.Code == line.Code).Select(l => l.Data);
var original = string.Join(" ", strings);
}
Data looks something like this: "123456789, 987654321, 32132, 7873892 ..."
But I get an OutOfMemoryException. Why? each string is approximatly 100-150 characters and there are 5-10 strings in the list.
Is there a better way then the string.Join?
Try this (and let us know if you get the same error):
lines.GroupBy(l => l.Code).Select(l => string.Join(" ", l.Select (x => x.Data)));
foreach (var line in lines.GroupBy(p=>p.Code))
{
var original = string.Join(" ", line.Select(p=>p.Data));
}
The StringBuild() class can join strings and isn't immutable.
Here's an MSDN article talking about immutable string vs how StringBuilder works.
http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.71).aspx

Categories