result shows System.String[] - c#

On my GetBusiness.aspx page i have create a test list
List<string> l = new List<string>();
l.Add("one");
l.Add("two");
l.Add("three");
l.Add("four");
l.Add("five");
// B.
string[] s = l.ToArray();
Response.Write(s);
No on my second page(default aspx page) I have some jQuery to load this array and show the results:
$.get('GetBusiness.aspx', function (returndata) {
// for each address in returndata
alert(returndata);
but the result is : System.String[]
If I iterate , he iterate the string "System.String[]"
$.each(returndata, function (index, value) {
alert(index + ': ' + value);
};
How can I show the results from the string array?

Change Response.Write(s) to :
JavaScriptSerializer objSerializer = new JavaScriptSerializer();
Response.Write(objSerializer.Serialize(s));
Reference: JavaScriptSerializer

In your GetBusiness page, you are outputting the .ToString() property of the array, which is "System.String[]". You need to iterate the list and output each element separatly in some usable format, like JSON and then parse appropriately.
Example (untested):
string reponse = "";
response += "{ \"Output\":[";
for(int i = 0; i < s.Length; i++) {
response += s[i];
if (i < s.Length - 1) response += ", "
}
response += "] }";
Response.Write(response);

List<string> l = new List<string>();
l.Add("one");
l.Add("two");
l.Add("three");
l.Add("four");
l.Add("five");
// B.
string[] s = l.ToArray();
Response.Write(string.Join(",", s));
javascript:
$.get('GetBusiness.aspx', function(returndata) {
var arr = returndata.split(',');
$.each(arr, function(index, value) {
alert(index + ': ' + value);
});
});

Related

Convert csv file to json which has two colums in a row and has multiple lines

I have a csv file and in one row i have two columns with multiple values .I want to convert that as a list
Example:
CSV data
Id name parentid
1 sam 12-george
24-jennifer
Json Data
[{ id:1, name:sam, parentid:[{ id:12, name:george }, { id:24, name:jennifer }] } ]
class Program
{
const string CSV =
#"Id name parentid
1 sam 12-george
24-jennifer";
static void Main(string[] args)
{
var csvArray = new JArray();
// Split to lines
string[] lines = CSV.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
// Ignore header line
JArray currentParentArray = null;
for (int i = 1; i < lines.Length; i++)
{
string[] items = lines[i].Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (items.Length == 3)
{
var line = new JObject();
csvArray.Add(line);
line["id"] = int.Parse(items[0]);
line["name"] = items[1];
currentParentArray = new JArray();
line["parentid"] = currentParentArray;
ParseParentId(items[2], currentParentArray);
}
if (items.Length == 1 && currentParentArray != null)
ParseParentId(items[0], currentParentArray);
}
var ser = JsonSerializer.CreateDefault();
string json = csvArray.ToString();
Console.WriteLine(json);
Console.ReadKey();
}
static void ParseParentId(string parentId, JArray parentArray)
{
int idx = parentId.IndexOf("-");
string id = parentId.Substring(0, idx);
string name = parentId.Substring(1 + idx);
var obj = new JObject();
obj["id"] = int.Parse(id);
obj["name"] = name;
parentArray.Add(obj);
}
}
This C# source should work. The array of parentid is remembered between lines and added to if the next line contains only another parentid.
Add a Nuget reference to Newtonsoft.Json to compile.

How to add json property to a Json.net Array

I want to add a property to the List in C#, then I want to create a JObject to set the value and sum some values ​​after, then I need to convert my List <Object> to a JArray, then to I want To add my jsonObject to JArray, then to return my JArray in Json form for display on screen or to go througt the JsonArray to show each result on a javascript table, but at the end the only thing I get is this error:
"Uncaught TypeError: Cannot use 'in' operator to search for 'length'
in [{"client":{"id":1001,"debtJanuary":500000"....
double total = 0;
JArray jsonarray = null;
JObject jsonobject = null;
List<ClientAccount> list = null;
try
{
list = ClientBussinesLayer.getListClientCash(id);
for(ClientAccount item in list)
{
total += item.debtJanuary + item.debtFebruary + item.debtMarch;
}
jsonobject = new JObject();
jsonobject.Add("totalDebt", total);
jsonobject.Add("statusList", "success");
jsonarray = JArray.FromObject(list);
jsonarray.Add(jsonObject);
}catch(Exception ex)
{
error
}
return JsonConvert.SerializeObject(jsonarray);
fnSuccessList: function (data) {
var strHtml = '';
var list = jQuery.parseJSON(data); //also i tried with data.d but dont work
$.each(list, function (index, item) {
strHtml += '<tr>';
strHtml += ' <td>' + item.debtJanuary + '</td>';
strHtml += ' <td>' + item.debtFebruary + '</td>';
strHtml += ' <td>' + item.debtMarch + '</td>';
strHtml += '</tr>'
});
$("#table").append(strHtml);
}
You should use foreach loop instead for:
foreach(var item in list)
{
total += item.debtJanuary+item.debtFebruary + item.debtMarch;
}

C# how write the whole array if string contains keyword

I am searching if a string within an stringarray contains a keyword.
If a string gets a match i want the array(s) which the string was found in to be output on the console.
Sofar i have managed to output every string that contains a keyword within the stringarray.
I have tried to work around this by outputting the array insteed but then i get this message "System.String[]"
However, that is not my intent. I wanted the array to be displayed. I wonder, how can i do this?
//Sorry for bad english.
Here are the relevant parts from my code:
List<string[]> loggbok = new List<string[]> { };
string[] log = new string[3]; //date, title, post
DateTime date = DateTime.Now;
log[0] = "\n\tDate: " + date.ToLongDateString() + " Time: " + date.ToShortTimeString();
Console.Write("\tTitle: ");
log[1] = "\tTitle: " + Console.ReadLine();
Console.Write("\tPost: ");
log[2] = "\tPost: " + Console.ReadLine();
loggbok.Add(log);
log = new string[3];
Console.Write("\n\tSearch: ");
string keyWord;
keyWord = Console.ReadLine();
foreach (string[] item in loggbok)
{
foreach (var s in item)
{
if (s.Contains(keyWord))
{
Console.WriteLine(item);
}
}
}`enter code here`
For displaying the whole array try this:
Console.WriteLine(String.Join("\r\n", item));
You can filter the array like this:
Console.WriteLine(String.Join("\r\n", item.Where(item => item.Contains(keyWord)).ToArray());
or
string[] filtered = item.Where(s => s.Contains(keyWord)).ToArray();
Console.WriteLine(String.Join("\r\n", filtered));
If you want to filter the whole loggbok (list of string arrays) use the SelectMany extension.
string[] filtered = loggbok.SelectMany(s => s.Contains(keyWord)).ToArray();
Console.WriteLine(String.Join("\r\n", filtered));
If I understand your question correctly, you want the whole array in which the keyword has been found.
What you do wrong is you state Console.WriteLine(item) which will only print that item.
Instead, make a function which returns true if the keyword has been found in this array and false if this has not happened. Your code would look something like this:
string keyWord;
keyWord = Console.ReadLine();
foreach (string[] item in loggbok)
{
if (checkItem(item)) {
for(int i = 0; i < item.Length; i++){
Console.WriteLine(item[i]);
}
}
}
public bool checkItem(string[] item, string keyWord) {
foreach(var s in item) {
if(s.Contains(keyWord))
return true;
}
return false;
}
This might help you.

Create comma separated string from portion of strings in C# List

I have a C# List that I want to create a comma separate string. I've found other answers on SO that deal with this, but my particular case I want to only use a portion of the values in the List to create the string.
If my List contained these values:
"Foo"
"Bar"
"Car"
and I wanted to create a string
Foo, Bar and Car.
I could use this code:
string.Format("{0} and {1}.",
string.Join(", ", myList.Take(myList.Count - 1)),
myList.Last());
However, my list is actual formed of jSON values like so
{ Name = "Foo" }
{ Name = "Bar" }
{ Name = "Car" }
So the above code results in:
{ Name = "Foo" }, { Name = "Bar" } and { Name = "Car" }.
How would I construct the string such that I only use the Foo, Bar and Car values in the list?
Update
Thanks to #StevePy, this is what I ended up with:
string.Format("{0} and {1}.",
string.Join(", ", myList.Select(x => x.Name).ToList().Take(myList.Count - 1)),
myList.Select(x => x.Name).ToList().Last());
If you need to operate with strings, just grab the necessary part of each string with, for example, String.IndexOf and String.LastIndexOf methods:
List<string> myList = new List<string> {
"{ Name = \"Foo\" }",
"{ Name = \"Bar\" }",
"{ Name = \"Car\" }"
};
var temp = myList.Select(x =>
{
int index = x.IndexOf("\"") + 1;
return x.Substring(index, x.LastIndexOf("\"") - index);
})
.ToList();
string result = string.Format("{0} and {1}.",
string.Join(", ", temp.Take(myList.Count - 1)),
temp.Last());
Linq should help.
var nameList = myList.Select(x=>x.Name).ToList();
you can use JsonConvert.toString to get the value of your list item, or if you used a json serialization, you could use the JsonConvert.Deserialization
I built a method that will do this for you:
static string ConvertToMyStyle(List<string> input)
{
string result = "";
foreach(string item in input)
{
if(input.IndexOf(item) != input.ToArray().Length-1)
result += item + ", ";
else
result += "and " + item + ".";
}
return result;
}
this handles the single item case
protected string FormatWithOxfordCommas(List<string> reasons)
{
string result = "";
if (reasons.Count == 1)
result += reasons[0];
else
{
foreach (string item in reasons)
{
if (reasons.IndexOf(item) != reasons.Count - 1)
result += item + ", ";
else
result += "and " + item + ".";
}
}
return result;
}

Join collection of objects into comma-separated string

In many places in our code we have collections of objects, from which we need to create a comma-separated list. The type of collection varies: it may be a DataTable from which we need a certain column, or a List<Customer>, etc.
Now we loop through the collection and use string concatenation, for example:
string text = "";
string separator = "";
foreach (DataRow row in table.Rows)
{
text += separator + row["title"];
separator = ", ";
}
Is there a better pattern for this? Ideally I would like an approach we could reuse by just sending in a function to get the right field/property/column from each object.
string.Join(", ", Array.ConvertAll(somelist.ToArray(), i => i.ToString()))
static string ToCsv<T>(IEnumerable<T> things, Func<T, string> toStringMethod)
{
StringBuilder sb = new StringBuilder();
foreach (T thing in things)
sb.Append(toStringMethod(thing)).Append(',');
return sb.ToString(0, sb.Length - 1); //remove trailing ,
}
Use like this:
DataTable dt = ...; //datatable with some data
Console.WriteLine(ToCsv(dt.Rows, row => row["ColName"]));
or:
List<Customer> customers = ...; //assume Customer has a Name property
Console.WriteLine(ToCsv(customers, c => c.Name));
I don't have a compiler to hand but in theory it should work. And as everyone knows, in theory, practice and theory are the same. In practice, they're not.
I found string.Join and lambda Select<Func<>> helps to write minimum code.
List<string> fruits = new List<string>();
fruits.Add("Mango");
fruits.Add("Banana");
fruits.Add("Papaya");
string commaSepFruits = string.Join(",", fruits.Select(f => "'" + f + "'"));
Console.WriteLine(commaSepFruits);
List<int> ids = new List<int>();
ids.Add(1001);
ids.Add(1002);
ids.Add(1003);
string commaSepIds = string.Join(",", ids);
Console.WriteLine(commaSepIds);
List<Customer> customers = new List<Customer>();
customers.Add(new Customer { Id = 10001, Name = "John" });
customers.Add(new Customer { Id = 10002, Name = "Robert" });
customers.Add(new Customer { Id = 10002, Name = "Ryan" });
string commaSepCustIds = string.Join(", ", customers.Select(cust => cust.Id));
string commaSepCustNames = string.Join(", ", customers.Select(cust => "'" + cust.Name + "'"));
Console.WriteLine(commaSepCustIds);
Console.WriteLine(commaSepCustNames);
Console.ReadLine();
// using System.Collections;
// using System.Collections.Generic;
// using System.Linq
public delegate string Indexer<T>(T obj);
public static string concatenate<T>(IEnumerable<T> collection, Indexer<T> indexer, char separator)
{
StringBuilder sb = new StringBuilder();
foreach (T t in collection) sb.Append(indexer(t)).Append(separator);
return sb.Remove(sb.Length - 1, 1).ToString();
}
// version for non-generic collections
public static string concatenate<T>(IEnumerable collection, Indexer<T> indexer, char separator)
{
StringBuilder sb = new StringBuilder();
foreach (object t in collection) sb.Append(indexer((T)t)).Append(separator);
return sb.Remove(sb.Length - 1, 1).ToString();
}
// example 1: simple int list
string getAllInts(IEnumerable<int> listOfInts)
{
return concatenate<int>(listOfInts, Convert.ToString, ',');
}
// example 2: DataTable.Rows
string getTitle(DataRow row) { return row["title"].ToString(); }
string getAllTitles(DataTable table)
{
return concatenate<DataRow>(table.Rows, getTitle, '\n');
}
// example 3: DataTable.Rows without Indexer function
string getAllTitles(DataTable table)
{
return concatenate<DataRow>(table.Rows, r => r["title"].ToString(), '\n');
}
In .NET 4 you can just do string.Join(", ", table.Rows.Select(r => r["title"]))
You could write a function that transforms a IEnumerable<string> into a comma-separated string:
public string Concat(IEnumerable<string> stringList)
{
StringBuilder textBuilder = new StringBuilder();
string separator = String.Empty;
foreach(string item in stringList)
{
textBuilder.Append(separator);
textBuilder.Append(item);
separator = ", ";
}
return textBuilder.ToString();
}
You can then use LINQ to query your collection/dataset/etc to provide the stringList.
As an aside: The first modification I would make is to use the StringBuilder Class instead of just a String - it'll save resources for you.
I love Matt Howells answer in this post:
I had to make it into an extension:
public static string ToCsv<T>(this IEnumerable<T> things, Func<T, string> toStringMethod)
Usage (I am getting all the emails and turning them into a CSV string for emails):
var list = Session.Find("from User u where u.IsActive = true").Cast<User>();
return list.ToCsv(i => i.Email);
For collections you can use this method as well, for example:
string.Join(", ", contactsCollection.Select(i => i.FirstName));
You can select any property that you want to separate.
string strTest = "1,2,4,6";
string[] Nums = strTest.Split(',');
Console.Write(Nums.Aggregate<string>((first, second) => first + "," + second));
//OUTPUT:
//1,2,4,6
Here's my favorite answer adapted to the question,
and corrected Convert to ConvertAll:
string text = string.Join(", ", Array.ConvertAll(table.Rows.ToArray(), i => i["title"]));

Categories

Resources