convert listbox value to comma separated string with single quotes - sql

i have a listbox with more than 100 items i want this 100 items to be comma separated with single quotes e.g: ''abc','def'' i want this to search in a select clause
List<string> SelectedValue = new List<string>();
foreach (ListItem lst in ListBox2.Items)
{
if (lst.Selected)
{
SelectedValue.Add(lst.Value);
}
}
string.Join(",",SelectedValue.Select(x=>string.Format("'{0}'",x)));
its giving me error 'the best overloaded method match for 'string.join has some invalid arguments, what an doing wrong here

Might I suggest a slightly different approach using a StringBuilder instead of putting the items into a List object? You are flatting these out to CSV anyways, so why not just build it that way like so..
var SB = new StringBuilder();
foreach (ListItem lst in ListBox2.Items)
{
if (lst.Selected)
{
SB.Append("'" + list.value + "',");
}
}
var FinalString = SB.ToString().Substring(0, (SB.Length - 1));

You linq query returns a result of type IEnumerable you must convert it to a string array:
List<string> selectedValue = (from ListItem lst in ListBox1.Items
where lst.Selected
select lst.Value).ToList();
//convert to array using ToArray()
string[] arr = selectedValue.Select(x => string.Format("'{0}'", x)).ToArray();
string data = string.Join(",",arr);

You need to convert the result of SelectedValue.Select to an array:
String result = string.Join(",", SelectedValue.Select(x => string.Format("'{0}'", x)).ToArray());`

Related

Get array of double from list of array of double, where first value in array is the max first value using linq

I want to get the array of doubles from a list of an array of doubles where the first value of the array is the highest value as compared to the first value of the other arrays in the list
For example, if the list of arrays are (4,5) , (-3,2) , (7,1) then it would return (7,1).
I tried this but no success:
Dim vertices as List(of Double()) = MethodToGetList()
dim rv as Double() = vertices.Select(Function(x As Double()) x.First.MaxValue).ToArray
Sorry, my basic is a bit rusty, I'll do it in C#, I hope you'll get the gist.
Whenever you want a LINQ function, where you need to examine every item of your sequence exactly once, and you want to do something with the item that is currently being examined, think of Aggregate.
This will initialize variable highestValue with your first source element; then it will compare every source element with the highestValue and keep the one that is highest:
List<List<double>> mySource = ...
var result = mySource.Aggregate( (highestValue, nextValue) =>
(nextValue[0] > highestValue[0]) ? nextValue : highestValue);
This will be similar to:
List<double> highestValue = mySource[0];
for (int i=1; i<mySource.Count; ++i)
{
if (mySource[i][0] > higestValue[0])
{
// found a new highestValue
highestValue = mySource[i];
}
// else: keep the highest value
}
It is easy to see, that this only works if mySource is not empty. If you have an empty source, you should think of what you want as a result. We will initialize with this emptyResult:
List<double> emptyResult = ... // what do you want to use if there is nothing in your source?
List<double> highestValue = emptyResult;
for (int i=0; i<mySource.Count; ++i)
{
if (mySource[i][0] > higestValue[0])
{
// found a new highestValue
highestValue = mySource[i];
}
}
And now in LINQ: use the other Aggregate:
var result = mySource.Aggregate(emptyResult, // use this as seeder
(nextValue[0] > highestValue[0]) ? nextValue : highestValue);
This will help if you have an empty sequence. Buf what if one of your Lists in the source is null or empty?
Let's assume you don't want to consider them at all:
var nonEmptyArrays = mySource.Where(list => list != null && list.Count != 0)
var result = noneEmptyArrays.Aggregate((emptyResult, // use this as seeder
(nextValue[0] > highestValue[0]) ? nextValue : highestValue);
Simple comme bonjour!
Try this. This orders the vertices list of arrays by the first position of each array, then by the second position of the array. Then in the case of the same data (below), the list would look like: (7,1), (7,2), .... Then last piece of the statement grabs the first element in the sorted list so would return (7, 1)
Dim rv As Double() = vertices.OrderByDescending(Function(v) v(0)).ThenBy(Function(v) v(1)).FirstOrDefault
Data to test:
Dim vertices As List(Of Double()) = New List(Of Double())
vertices.Add(New Double() {4, 5})
vertices.Add(New Double() {-1, 2})
vertices.Add(New Double() {7, 1})
vertices.Add(New Double() {7, 2})

Convert a Linq result to a datatable

I am trying to convert a Linq result in to a datatable
I have a linq that is created from a dataset of many tables. It returns results, but I need to get the results in to a new datatable.
Examples I have seen say I sould be able to use .CopyToDataTable But for some reason this doesn't work?
I have noticed that I can to .ToArray perhaps I can then turn the array in to a datatable? Seems line an unnecessary step?
Here is my query: (it works)
Dim R2 = From Inq In DS.Tables!CNLocalInquiry.AsEnumerable()
Join Cust In DS.Tables!CustomerID.AsEnumerable() On Inq.Field(Of Integer)("CNLocalInquiry_Id") Equals Cust.Field(Of Integer)("CNLocalInquiry_Id")
Select New With {.date = Inq.Field(Of String)("date"),
.CName = Cust.Field(Of String)("CustomerNumber"),
.Name = Cust.Field(Of String)("name")}
Dim MemberInq as new datatable
MemberInq = R2.CopyToDataTable() <-- this doesn't work
This is what my query returns:
(this is the easy to code way... this will not be performant for large datasets)
public static class ToolsEx
{
public static DataTable ToDataTable<T>(this IEnumerable<T> items)
{
var t = typeof(T);
var dt = new DataTable(t.Name);
var props = t.GetProperties()
.Select(p => new { N = p.Name, Getter = p.GetGetMethod() })
.Where(p => p.Getter != null)
.ToList();
props.ForEach(p => dt.Columns.Add(p.N));
foreach (var item in items)
dt.Rows.Add(props.Select(p => p.Getter.Invoke(item, null)).ToArray());
return dt;
}
}
I've saved this as an extension method and it's always worked perfectly:
https://msdn.microsoft.com/en-us/library/bb669096.aspx
Examples here:
https://msdn.microsoft.com/en-us/library/bb386921.aspx
Hope that does the trick!

String is to Substring, as ArrayList is to?

In Java, and many other languages, one can grab a subsection of a string by saying something like String.substring(begin, end). My question is, Does there exist a built-in capability to do the same with Lists in Java that returns a sublist from the original?
This method is called subList and exists for both array and linked lists. Beware that the list it returns is backed by the existing list so updating the original one will update the slice.
The answer can be found in the List API: List#subList(int, int) (can't figure out how to get the link working....)
Be warned, though, that this is a view of the underlying list, so if you change the original list, you'll change the sublist, and the semantics of the sublist is undefined if you structurally modify the original list. So I suppose it isn't strictly what you're looking for...
If you want a structurally independent subsection of the list, I believe you'll have to do something like:
ArrayList<something> copy = new ArrayList<>(oldList.subsection(begin, end));
However, this will retain references to the original objects in the sublist. You'll probably have to manually clone everything if you want a completely new list.
The method is called sublist and can be found here in the javadocs
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#subList(int, int)
You can use subList(start, end)
ArrayList<String> arrl = new ArrayList<String>();
//adding elements to the end
arrl.add("First");
arrl.add("Second");
arrl.add("Third");
arrl.add("Random");
arrl.add("Click");
System.out.println("Actual ArrayList:"+arrl);
List<String> list = arrl.subList(2, 4);
System.out.println("Sub List: "+list);
Ouput :
Actual ArrayList:[First, Second, Third, Random, Click]
Sub List: [Third, Random]
You might just want to make a new method if you want it to be exactly like substring is to String.
public static List<String> sub(List<String> strs, int start, int end) {
List<String> ret = new ArrayList<>(); //Make a new empty ArrayList with String values
for (int i = start; i < end; i++) { //From start inclusive to end exclusive
ret.add(strs.get(i)); //Append the value of strs at the current index to the end of ret
}
return ret;
}
public static List<String> sub(List<String> strs, int start) {
List<String> ret = new ArrayList<>(); //Make a new empty ArrayList with String values
for (int i = start; i < strs.size(); i++) { //From start inclusive to the end of strs
ret.add(strs.get(i)); //Append the value of strs at the current index to the end of ret
}
return ret;
}
If myStrings is an ArrayList of the following Strings: {"do","you","really","think","I","am","addicted","to","coding"}, then sub(myStrings,1,6) would return {"you", "really", "think", "I", "am"} and sub(myStrings,4) would return {"I", "am", "addicted", "to", "coding"}. Also by doing sub(myStrings, 0) it would rewrite myStrings as a new ArrayList which could help with referencing problems.

Does Dapper support the like operator?

Using Dapper-dot-net...
The following yields no results in the data object:
var data = conn.Query(#"
select top 25
Term as Label,
Type,
ID
from SearchTerms
WHERE Term like '%#T%'",
new { T = (string)term });
However, when I just use a regular String Format like:
string QueryString = String.Format("select top 25 Term as Label, Type, ID from SearchTerms WHERE Term like '%{0}%'", term);
var data = conn.Query(QueryString);
I get 25 rows back in the collection. Is Dapper not correctly parsing the end of the parameter #T?
Try:
term = "whateverterm";
var encodeForLike = term => term.Replace("[", "[[]").Replace("%", "[%]");
string term = "%" + encodeForLike(term) + "%";
var data = conn.Query(#"
select top 25
Term as Label,
Type,
ID
from SearchTerms
WHERE Term like #term",
new { term });
There is nothing special about like operators, you never want your params inside string literals, they will not work, instead they will be interpreted as a string.
note
The hard-coded example in your second snippet is strongly discouraged, besides being a huge problem with sql injection, it can cause dapper to leak.
caveat
Any like match that is leading with a wildcard is not SARGable, which means it is slow and will require an index scan.
Yes it does. This simple solution has worked for me everytime:
db.Query<Remitente>("SELECT *
FROM Remitentes
WHERE Nombre LIKE #n", new { n = "%" + nombre + "%" })
.ToList();
Best way to use this to add concat function in query as it save in sql injecting as well, but concat function is only support above than sql 2012
string query = "SELECT * from country WHERE Name LIKE CONCAT('%',#name,'%');"
var results = connection.query<country>(query, new {name});
The answer from Sam wasn't working for me so after some testing I came up with using the SQLite CONCAT equivalent which seems to work:
string sql = "SELECT * FROM myTable WHERE Name LIKE '%' || #NAME || '%'";
var data = IEnumerable data = conn.Query(sql, new { NAME = Name });
Just to digress on Sam's answer, here is how I created two helper methods to make searches a bit easier using the LIKE operator.
First, creating a method for generating a parameterized query, this method uses dynamic: , but creating a strongly typed generic method should be more desired in many cases where you want static typing instead of dynamic.
public static dynamic ParameterizedQuery(this IDbConnection connection, string sql, Dictionary<string, object> parametersDictionary)
{
if (string.IsNullOrEmpty(sql))
{
return null;
}
string missingParameters = string.Empty;
foreach (var item in parametersDictionary)
{
if (!sql.Contains(item.Key))
{
missingParameters += $"Missing parameter: {item.Key}";
}
}
if (!string.IsNullOrEmpty(missingParameters))
{
throw new ArgumentException($"Parameterized query failed. {missingParameters}");
}
var parameters = new DynamicParameters(parametersDictionary);
return connection.Query(sql, parameters);
}
Then adding a method to create a Like search term that will work with Dapper.
public static string Like(string searchTerm)
{
if (string.IsNullOrEmpty(searchTerm))
{
return null;
}
Func<string, string> encodeForLike = searchTerm => searchTerm.Replace("[", "[[]").Replace("%", "[%]");
return $"%{encodeForLike(searchTerm)}%";
}
Example usage:
var sql = $"select * from products where ProductName like #ProdName";
var herringsInNorthwindDb = connection.ParameterizedQuery(sql, new Dictionary<string, object> { { "#ProdName", Like("sild") } });
foreach (var herring in herringsInNorthwindDb)
{
Console.WriteLine($"{herring.ProductName}");
}
And we get our sample data from Northwind DB:
I like this approach, since we get helper extension methods to do repetitive work.
My solution simple to this problem :
parameter.Add("#nomeCliente", dfNomeCliPesquisa.Text.ToUpper());
query = "SELECT * FROM cadastrocliente WHERE upper(nome) LIKE " + "'%" + dfNomeCliPesquisa.Text.ToUpper() + "%'";

searching a list object

I have a list:
Dim list As New List(Of String)
with the following items:
290-7-11
1255-7-12
222-7-11
290-7-13
What's an easy and fast way to search if duplicate of "first block" plus "-" plus "second block" is already in the list. Example the item 290-7 appears twice, 290-7-11 and 290-7-13.
I am using .net 2.0
If you only want to know if there are duplicates but don't care what they are...
The easiest way (assuming exactly two dashes).
Boolean hasDuplicatePrefixes = list
.GroupBy(i => i.Substring(0, i.LastIndexOf('-')))
.Any(g => g.Count() > 1)
The fastest way (at least for large sets of strings).
HashSet<String> hashSet = new HashSet<String>();
Boolean hasDuplicatePrefixes = false;
foreach (String item in list)
{
String prefix = item.Substring(0, item.LastIndexOf('-'));
if (hashSet.Contains(prefix))
{
hasDuplicatePrefixes = true;
break;
}
else
{
hashSet.Add(prefix);
}
}
If there are cases with more than two dashes, use the following. This will still fail with a single dash.
String prefix = item.Substring(0, item.IndexOf('-', item.IndexOf('-') + 1));
In .NET 2.0 use Dictionary<TKey, TValue> instead of HashSet<T>.
Dictionary<String, Boolean> dictionary= new Dictionary<String, Boolean>();
Boolean hasDuplicatePrefixes = false;
foreach (String item in list)
{
String prefix = item.Substring(0, item.LastIndexOf('-'));
if (dictionary.ContainsKey(prefix))
{
hasDuplicatePrefixes = true;
break;
}
else
{
dictionary.Add(prefix, true);
}
}
If you don't care about readability and speed, use an array instead of a list, and you are a real fan of regular expressions, you can do the following, too.
Boolean hasDuplicatePrefixes = Regex.IsMatch(
String.Join("#", list), #".*(?:^|#)([0-9]+-[0-9]+-).*#\1");
Do you want to stop user from adding it?
If so, a HashTable with the key as first block-second block could be of use.
If not, LINQ is the way to go.
But, it will have to traverse the list to check.
How big can this list be?
EDIT: I don't know if HashTable has generic version.
You could also use SortedDictionary which can take generic arguments.
If you're list contains only strings, then you can simply make a method that takes the string you want to find along with the list:
Boolean isStringDuplicated(String find, List<String> list)
{
if (list == null)
throw new System.ArgumentNullException("Given list is null.");
int count = 0;
foreach (String s in list)
{
if (s.Contains(find))
count += 1;
if (count == 2)
return true;
}
return false;
}
If you're numbers have a special significance in your program, don't be afraid to use a class to represent them instead of sticking with strings. Then you would have a place to write all the custom functionality you want for said numbers.