To remove double quotation in string array - asp.net

In the below code i have a string array which holds values i want to remove double quotion in the array and display values like 1,2,3,4,5.Pls help me to do this.
DataSet Stock = Chart.ChartCurrentStock(LocationID);
List<string> StockDetails = new List<string>();
foreach (DataRow row in Stock.Tables[0].Rows)
{
StockDetails.Add(row["CurrentStock"].ToString());
}
string[] Stocks = StockDetails.ToArray();

I don't understand your code sample but: ( how it relates?)
If you have a string array and you want one final single string separated with "," :
string[] g = new string[]{"1","2","3"};
var s=string.Join(",",g);
Console.WriteLine (s); // "1,2,3"

Related

im using java. Here expected outcome should be Test.Testing, but it is returning all the data in the list. Any other way to replace *

List<String> list = new ArrayList<String>();
list.add("Test.Testing");
list.add("Test");
list.add("Testing");
String queryString = "*.*";
queryString = queryString.replaceAll("\\*" , ".*");
for (String str : list) {
if (str.matches(queryString))
System.out.println(str);
}
here expected answer should be
Test.Testing
but it is returning all the data in the list.

Return list of Integers with SQLiteDatabase.rawQuery

I'm trying to write a function that returns a list of Integers using SQLiteDatabase.rawQuery.
This is how i'm imagining it but doesn't work..
public List<Integer> queryInt(String sql, String[] whereArgs){
//fetch string array
List<Integer> r = new ArrayList<Integer> ();
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.rawQuery(
sql,
whereArgs
);
return c.toInt(); //something that does this
}
If someone has a clue, thanks for the help !
You need to move within the Cursor before you can access any of the data (initially a Cursor will be positioned at before the first row (position -1)).
So your queryInt method could be :-
public List<Integer> queryInt(String sql, String[] whereArgs){
//fetch string array
List<Integer> r = new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.rawQuery(
sql,
whereArgs
);
// Loop through the Cursor
while(c.moveToNext()) {
r.add(c.getInt(0)); //<<<< see note
}
c.close(); //<<<< Should always close a Cursor when done with it.
return r;
}
Note 0 assumes that the data is to be extracted from the first column. However it is considered better practice to not hard code the column offset but to get the column offset based upon the column name so r.add(c.getInt(c.getColumnIndex(your_column_name_as_a_string))); would be recommended.
If there are no rows then the above would return an empty List, so you may need to check the returned List's size.

Json adds \ charcter while returning json format

I am creating an API/web service which needs to return JSON format.
I also need to create the web service as a POST request
Sample code below, see more snippets of the source code in the end of this post.
Meta meta = new Meta();
meta.recipes = new List<Recipe>();
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(meta);
return strJSON;
Problem:
When I try the response in a few REST consoles (list of consoles tried) and in the ASP.NET client, I get this format with an extra "d" and extra \ before each ". See return output below:
{"d":"{\"count\":\"0\",\"status\":\"500\",\"recipes\":[]}"}
When I try to remove serialization then I get the following format:
<Meta xmlns:xsi="w3.org/2001/XMLSchema-instance"; xmlns:xsd="w3.org/2001/XMLSchema"; xmlns="tempuri.org/">; <count>1</count> <status>200</status> <recipes> <Recipe> <recipeID>1</recipeID> <recipeName>Apple Pie</recipeName> <imageURL>service/it.jpg</imageURL> <rating/> </Recipe> </recipes> </Meta>
But I want it in the following format:
{"count":"0","status":"500","recipes":[]}
[WebMethod(Description = "Return all Recipe...")]
[ScriptMethod( ResponseFormat = ResponseFormat.Json)]
public Meta RecipeList(string ingredientId, string cuisineId, string dishTypeId, string courseId)
This still returns XML even though I return meta object and don't add serialization
Questions:
I thought the correct JSON format should be WITHOUT this "d" and the . Is this true or is the correct JSON format of the output actually WITH the "d" and the \?
If it should be without, then where do you suggest the correction should be made, on the server side or in the client side?
How should I correct this on the server side?
How can this be corrected on the client side?
[WebMethod(Description = "Return all Recipe...")]
[ScriptMethod( ResponseFormat = ResponseFormat.Json)]
public string RecipeList(string ingredientId, string cuisineId, string dishTypeId, string courseId,
string occasionId, string considerationId, string recipeType, string readyTime, string favouritebyUserId, string bookmarkbyUserId)
{
DataSet ds = new DataSet();
int rTime = 0;
if (readyTime == "") rTime = 0;
else rTime = Convert.ToInt32(readyTime);
ds = RecipeBLL.SearchRecipe(ingredientId, cuisineId, dishTypeId, courseId, occasionId, considerationId, recipeType, rTime);
// Create a multidimensional jagged array
string[][] JaggedArray = new string[ds.Tables[0].Rows.Count][];
int i = 0;
Meta meta = new Meta();
int count = 0;
meta.recipes = new List<Recipe>();
foreach (DataRow rs in ds.Tables[0].Rows)
{
Recipe recipe = new Recipe {
recipeID = rs["RecipeId"].ToString(),
recipeName = rs["RecipeTitle"].ToString(),
imageURL = rs["Photo"].ToString(),
rating = rs["Rating"].ToString()
};
meta.recipes.Add(recipe);
//mlist.Add(recipe);
count++;
}
if (count != 0)
meta.status = "200";
else
meta.status = "500";
meta.count = count.ToString();
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON1 = js.Serialize(meta);
return strJSON1;
}
It sounds like the problem is that you're returning a string from your code somewhere - and then it's being encoded as JSON by something else. So the string you're returning is:
{"count":"0","status":"500","recipes":[]}
... but whatever you're returning from thinks you're trying to return a string, rather than an object with a count etc.
You haven't shown any of your code, but I suspect the answer will be to just remove one explicit serialization call.

Insert word before last word in a string

I am trying to insert the word "and" before the last word in a string. This is my code so far:
string skillset = "";
foreach (ListItem item in SkillSet.Items)
{
if (item.Selected)
{
skillset += item.Text + ", ";
}
}
skillset = skillset.Substring(0, skillset.Length - 2);
Any help is greatly appreciated.
Thanks
Thomas
If you just want to put "and" in fron of the last word you can use to split your string into an array of strings, change the last word and join the string back together. It would look something like this
string[] skills = skillset.Split(new char[] { ',' });
skills[skills.Length-1] = "and " + skills[skills.Length-1];
skillset = string.Join(",", skills);
This returns a new string in which a specified string is inserted at a specified index position.
Example
string str = "We are loudly";
string mynewvalue = "talking";
str.Insert(str.Length - 1, mynewvalue);
int myStringLength = myString.length;
string myString = inputString.Substring(0, myStringLength);
int index = myString.LastIndexOf(' ');
string outputString = myString.Insert(index , " and ");
Example : http://www.dotnetperls.com/insert

datagrid rows to save in collection and show on another page asp.net

I have grid in my page which have four columns with multiple rows
Userid username stateid and statename
which collection i should use to send data to another page using session
my code is
string[] strArray = new string[] {};
foreach (GridViewRow gr in gvCompany.Rows)
{
strArray =new string[4] {new[] {gr.Cells[0].Text}.ToString(), new[] {gr.Cells[1].Text}.ToString(), new[] {gr.Cells[2].Text}.ToString(),new[] {gr.Cells[3].Text}.ToString()};
}
Session["List"] = strArray;
Response.Redirect("Tid.aspx?Mode=List");
on tid page my code is
string[] ls = new string[] { };
ls =(string[]) Session["List"];
foreach (string st in ls )
{
//get each cell
}
but value of st is system.string rather than value
Using an string[] is not recommended since the more fields will add in future the difficult it will get to keep the field and index relationship bug free..
You can create a proper class object eg. Company and pass a List to other class, List is in System.Collections.Generic namespace.

Resources