i have a gridview
INSEE1 Commune
------ -------
10002 AILLEVILLE
10003 BRUN
i have a script that return a list of object.
List<object> Temp = ASPxGridView_Insee.GetSelectedFieldValues("INSEE1");
my Temp is a list of object of INSSE1 that i have selected.
but now i add Commune also, so my script become:
List<object> Temp = ASPxGridView_Insee.GetSelectedFieldValues("INSEE1","Commune");
and my Temp is list of object of INSEE1 and Commune look at image:
how can i acces 10002 and AILLEVILLE ?
i have try with cast it of my Pers_INSEE class:
public class Pers_InseeZone
{
string _Code_Insee;
public string Code_Insee
{
get { return _Code_Insee; }
set { _Code_Insee = value; }
}
string _Commune;
public string Commune
{
get { return _Commune; }
set { _Commune = value; }
}
}
foreach (var oItem in Temp )
{
Pers_InseeZone o = (Pers_InseeZone)oItem;
}
but I not work, I can not cast it.
I have tried like this:
foreach (var oItem in Temp )
{
var myTempArray = oItem as IEnumerable;
foreach (var oItem2 in myTempArray)
{
string res= oItem2.ToString();
....
the value of res = 10002, but how can I get the value of AILEVILLE ?
the value of Temp[0].GetType(); is:
Thanks in advance
Ok I thought so, so as already mentioned in the comments you have a array of objects inside each object so you need to cast first every object in your list into an array of objects: object[] then you can access each part. Here is an example that recreates your problem:
object[] array = new object[] {10002, "AILEEVILLE"};
List<object> Temp = new List<object> {array};
And the solution:
// cast here so that the compiler knows that it can be indexed
object [] obj_array = Temp[0] as object[];
List<Pers_InseeZone> persList = new List<Pers_InseeZone>();
Pers_InseeZone p = new Pers_InseeZone()
{
Code_Insee = obj_array[0].ToString(),
Commune = obj_array[1].ToString()
};
persList.Add(p);
Applied to your code it would look something like this:
List<object> Temp = ASPxGridView_Insee.GetSelectedFieldValues("INSEE1","Commune");
List<Pers_InseeZone> persList = new List<Pers_InseeZone>();
foreach (object oItem in Temp )
{
object [] obj_array = oItem as object[];
Pers_InseeZone p = new Pers_InseeZone()
{
Code_Insee = obj_array[0].ToString(),
Commune = obj_array[1].ToString()
};
persList.Add(p);
}
The problem is down to the fact your class doesn't match the same structure as the data you are getting, so it can't be cast into it.
Instead why don't you just iterate over the results and build a new instance of the class?
var tempList = new List<Pers_InseeZone>();
foreach (var oItem in Temp)
{
tempList.Add(new Pers_InseeZone(oItem[0], oItem[1]));
}
You will need to add a constructor to your Pers_InseeZone class, and assign the variables there.
Related
this is my .csv file:
Apple,rose,tiger
Mango,lily,cheetah
Banana,sunflower,lion
Apple,marigold,cat
input: Mango (i write it in the text box)
desired output:
Flower = lily; Animal = cheetah
similarly,
input: Apple
desired output:
Flower = rose,marigold; Animal = tiger,cat
this is the code i have written:
private void button1_Click(object sender, EventArgs e)
{
using (var reader = new StreamReader(#"C:\asp_net\abc.csv"))
{
List<string> listA = new List<string>();
List<string> listB = new List<string>();
List<string> listC = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
listA.Add(values[0]);
listB.Add(values[1]);
listC.Add(values[2]);
}
string checkThis = obj.SearchSenSig(textBox1.Text);
if (listA.Any(checkThis.Contains))
{
int count = listA.Where(x => x.Equals(checkThis)).Count();
if (count == 1)
{
int index = listA.IndexOf(checkThis);
var firstItem = listB.ElementAt(index);
var secondItem = listC.ElementAt(index);
MessageBox.Show(String.Format("receiver = {0}, url = {1}", firstItem, secondItem));
}
else
{
foreach (string item in listA)
{
int i = listA.IndexOf(item);
bool result = item.Equals(checkThis);
if (result)
{
List<string> myCollection1 = new List<string>();
myCollection1.Add(listB.ElementAt(i));
string firstItem = string.Join(",", myCollection1);
List<string> myCollection2 = new List<string>();
myCollection2.Add(listC.ElementAt(i));
string secondItem = string.Join(",", myCollection2);
MessageBox.Show(String.Format("Flower = {0}, Animal = {1}", firstItem, secondItem));
}
}
}
}
else
{
MessageBox.Show("The search element does not exists.");
}
}
Still i am not getting the desired output. Please help.
Instead of creating a different list for each column, create a single class to hold an entire row data:
class Data // I'll bet you can find a better name for this class...
{
public string Fruit {get;set;}
public string Flower {get;set;}
public string Animal {get;set;}
}
and populate a list of this class:
private List<Data> data = new List<Data>(); // note: this is a field, not a local variable.
Populating this list should be done only once, in the constructor or in the form_load event:
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
data.Add(
new Data()
{
Fruit = values[0],
Flower = values[1],
Animal = values[2]
}
);
}
Now all you have to do in the button_click event handler is get all the items corresponding to your search string. Assuming you are only searching for fruits using the FindAll method and display the results:
var result = data.FindAll(d => d.Fruit == searchString);
This will return a list of Data where the Fruit property contains the same string as searchString. use linq and string.Join to format the results into a string:
var resultString = $"Flower = {string.Join(",", result.Select(r => r.Flower))}; Animal = {string.Join(",", result.Select(r => r.Animal))}";
I am pulling some data from a BigQuery table using the code below in C#
BigQueryClient client = BigQueryClient.Create("<Project Name>");
BigQueryTable table = client.GetTable("<Database>", "Students");
string sql = $"select * FROM {table} where Marks='50'";
BigQueryResults results = client.ExecuteQuery(sql);
foreach (BigQueryRow row in results.GetRows())
{
}
I want to be able to either read the entire results variable into JSON or be able to get the JSON out of each row.
Of course, I could create a class that models the table. And inside the foreach loop, I could just read each row into the class object. The class object I can try to serialize into JSON using a third party like "newton soft".
Something like :
class Student{
int id; // assume these are columns in the db
string name;
}
My foreach would now look like:
foreach (BigQueryRow row in results.GetRows())
{
Student s=new Student();
s.id = Convert.ToString(row["id"]);
s.name= Convert.ToString(row["name"]);
// something like string x=x+ s.toJSON(); //using newton soft
}
This way string x will have the JSON generated and appended for each row.
Or is there a way I can just add each student to a collection or List and then get the JSON from the whole list?
This whole reading row by row and field by field seems tedious to me and there must be a simpler way I feel. Did not see any support from Google BigQuery for C# to directly convert to JSON. They did have something in Python.
If not then the list to JSON would be better but I am not sure if it supported.
Update :
https://github.com/GoogleCloudPlatform/google-cloud-dotnet/blob/master/apis/Google.Cloud.BigQuery.V2/Google.Cloud.BigQuery.V2/BigQueryRow.cs
Looks like the Big Query Row class has a RawRow field which is of Type TableRow. And the class uses JSON references so , I am sure they have the data of the row in JSON format . How can I expose it to me ?
This might be a little late but you can use:
var latestResult = _bigQueryClient.ExecuteQuery($"SELECT TO_JSON_STRING(t) FROM `{ProjectId}.{DatasetId}.{TableName}` as t", null
All columns will be serialized as json and placed in the first column on each row. You can then use something like Newtonsoft to parse each row easily.
I ran into the same issue.
I am posting this solution which is not optimized for performance but very simple for multiple data types.
This allows you to deserialize anything (almost)
public class BQ
{
private string projectId = "YOUR_PROJECT_ID";
public BQ()
{
}
public List<T> Execute<T>(string sql)
{
var client = BigQueryClient.Create(projectId);
List<T> result = new List<T>();
try
{
string query = sql;
BigQueryResults results = client.ExecuteQuery(query, parameters: null);
List<string> fields = new List<string>();
foreach (var col in results.Schema.Fields)
{
fields.Add(col.Name);
}
Dictionary<string, object> rowoDict;
foreach (var row in results)
{
rowoDict = new Dictionary<string, object>();
foreach (var col in fields)
{
rowoDict.Add(col, row[col]);
}
string json = Newtonsoft.Json.JsonConvert.SerializeObject(rowoDict);
T o = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
result.Add(o);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
client.Dispose();
Console.WriteLine("Done.");
}
return result;
}
}
You can use Newtonsoft.Json. First download by PackageManager Console the Nuget Package, here you can get the command to do that.
After download you can use it as the following code:
List<Student> list = new List<Student>();
foreach (BigQueryRow row in results.GetRows())
{
Student s=new Student();
s.id = Convert.ToString(row["id"]);
s.name= Convert.ToString(row["name"]);
list.Add(s);
}
var jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(list);
I hope this can help you.
Here is the complete solution for casting BigQueryResults or GetQueryResultsResponse or QueryResponse data to Model/JSON format using C# reflection:
public List<T> GetBQAsModel<T>(string query) where T : class, new()
{
var bqClient = GetBigqueryClient();
var res = bqClient.ExecuteQuery(query, parameters: null);
return GetModels<T>(res);
}
private List<T> GetModels<T>(BigQueryResults tableRows) where T : class, new()
{
var lst = new List<T>();
foreach (var item in tableRows)
{
var lstColumns = new T().GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList();
var newObject = new T();
for (var i = 0; i < item.RawRow.F.Count; i++)
{
var name = item.Schema.Fields[i].Name;
PropertyInfo prop = lstColumns.FirstOrDefault(a => a.Name.ToLower().Equals(name.ToLower()));
if (prop == null)
{
continue;
}
var val = item.RawRow.F[i].V;
prop.SetValue(newObject, Convert.ChangeType(val, prop.PropertyType), null);
}
lst.Add(newObject);
}
return lst;
}
private List<T> GetModels<T>(GetQueryResultsResponse getQueryResultsResponse) where T : class, new()
{
var lst = new List<T>();
foreach (var item in getQueryResultsResponse.Rows)
{
var lstColumns = new T().GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList();
var newObject = new T();
for (var i = 0; i < item.F.Count; i++)
{
var name = getQueryResultsResponse.Schema.Fields[i].Name;
PropertyInfo prop = lstColumns.FirstOrDefault(a => a.Name.ToLower().Equals(name.ToLower()));
if (prop == null)
{
continue;
}
var val = item.F[i].V;
prop.SetValue(newObject, Convert.ChangeType(val, prop.PropertyType), null);
}
lst.Add(newObject);
}
return lst;
}
private List<T> GetModels<T>(QueryResponse queryResponse) where T : class, new()
{
var lst = new List<T>();
foreach (var item in queryResponse.Rows)
{
var lstColumns = new T().GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList();
var newObject = new T();
for (var i = 0; i < item.F.Count; i++)
{
var name = queryResponse.Schema.Fields[i].Name;
PropertyInfo prop = lstColumns.FirstOrDefault(a => a.Name.ToLower().Equals(name.ToLower()));
if (prop == null)
{
continue;
}
var val = item.F[i].V;
prop.SetValue(newObject, Convert.ChangeType(val, prop.PropertyType), null);
}
lst.Add(newObject);
}
return lst;
}
I would do something like this:
var res = Result. Getrows. Select(x=> new student(){id=x[`ID']}).
And then:
var js = json. Conver(res);
This way is much faster and clearer.
I want a function which takes in a datatable & returns a List (object is not DataRow)
Eg. :
I know I can do this (but this requires column names to be known) :
// Datatable dt = Filled from a Database query & has 3 columns Code,Description & ShortCode
List<object> rtn = new List<object>();
var x = from vals in dt.Select()
select new
{
Code = vals["Code"],
Description = vals["Description"],
ShortCode = vals["ShortCode"],
};
rtn.AddRange(x)
return rtn;
What i want is a generic version so that i can pass in any datatable & it will generate based on column names in the datatable.
Since the property names are not known at compile time and you want to use the data for JSON serialization, you can use the following to create a list of dictionary. If you use Newtonsoft JSON, then the serialization takes care of converting the key value pairs in a JSON object format.
IEnumerable<Dictionary<string,object>> result = dt.Select().Select(x => x.ItemArray.Select((a, i) => new { Name = dt.Columns[i].ColumnName, Value = a })
.ToDictionary(a => a.Name, a => a.Value));
In order to dynamically create properties so as to treat different dataTables with different set of Columns, we can use the System.Dynamic.ExpandoObject. It basically implements, IDictionary <string,object>. The format, which can easily be converted to JSON.
int colCount = dt.Columns.Count;
foreach (DataRow dr in dt.Rows)
{
dynamic objExpando = new System.Dynamic.ExpandoObject();
var obj = objExpando as IDictionary<string, object>;
for (int i = 0; i < colCount; i++)
{
string key = dr.Table.Columns[i].ColumnName.ToString();
string val = dr[key].ToString();
obj[key] = val;
}
rtn.Add(obj);
}
String json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(rtn);
You can use the following generic function:-
private static List<T> ConvertDataTable<T>(DataTable dt)
{
List<T> data = newList<T>();
foreach (DataRowrow in dt.Rows)
{
Titem = GetItem<T>(row);
data.Add(item);
}
return data;
}
private static TGetItem<T>(DataRow dr)
{
Type temp = typeof(T);
T obj =Activator.CreateInstance<T>();
foreach (DataColumncolumn in dr.Table.Columns)
{
foreach (PropertyInfopro in temp.GetProperties())
{
if (pro.Name == column.ColumnName)
pro.SetValue(obj,dr[column.ColumnName], null);
else
continue;
}
}
return obj;
}
Please check my article, which has complete demonstration on how to use this generic method.
Here is the original question:
// Datatable dt = Filled from a Database query & has 3 columns Code,Description & ShortCode
List<object> rtn = new List<object>();
var x = from vals in dt.Select()
select new
{
Code = vals["Code"],
Description = vals["Description"],
ShortCode = vals["ShortCode"],
};
rtn.AddRange(x)
return rtn;
Just replace with
List<object> rtn = JsonConvert.DeserializeObject<List<object>>(JsonConvert.SerializeObject(dt));
You will have the provide the anonymous object as a parameter and use json/xml serialization:
protected static List<T> ToAnonymousCollection<T>(DataTable dt, T anonymousObject)
{
List<DataColumn> dataColumns = dt.Columns.OfType<DataColumn>().ToList();
return dt.Rows.OfType<DataRow>().Select(dr =>
{
Dictionary<string, object> dict = new Dictionary<string, object>();
dataColumns.Each(dc => dict.Add(dc.ColumnName, dr[dc]));
return JsonConvert.DeserializeAnonymousType(JsonConvert.SerializeObject(dict), anonymousObject);
}).ToList();
}
Usage:
var anonymousCollection = ToAnonymousCollection(dt, new { Code = [ColumnTypeValue, eg. 0], Description = [ColumnTypeValue, eg. string.Empty], ShortCode = Code=[ColumnTypeValue, eg. 0] })
So I've been looking to set a default value for my combobox. I found a few things but none of them seem to work.
Actually, it works if I create a simple combobox and use comboBox1.SelectedIndex = comboBox1.Items.IndexOf("something") but once I dynamically generate the contents of the comboboxes, I can't get it to work anymore.
This is how I fill my combo box (located in the class's constructor);
string command = "SELECT category_id, name FROM CATEGORY ORDER BY name";
List<string[]> list = database.Select(command, false);
cbxCategory.Items.Clear();
foreach (string[] result in list)
{
cbxCategory.Items.Add(new ComboBoxItem(result[1], result[0]));
}
I can't seem to get it to work to set a default value, like if I place cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf("New") below the above code, it won't work.
WinForms, by the way.
Thank you in advance.
cbxCategory.SelectedIndex should be set to an integer from 0 to Items.Count-1 like
cbxCategory.SelectedIndex = 2;
your
cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf("New")
should return -1 as long as no ComboboxItem mutches the string ("New");
another solution though i don't like it much would be
foreach(object obj in cbxCategory.Items){
String[2] objArray = (String[])obj ;
if(objArray[1] == "New"){
cbxCategory.SelectedItem = obj;
break;
}
}
perhaps this also requires the following transformation to your code
foreach (string[] result in list)
{
cbxCategory.Items.Add(result);
}
I haven't tested the code and i am not sure about the casting to String[2] but something similar should work
It looks like you're searching the cbxCategory.Items collection for a string, but it contains items of type ComboBoxItem. Therefore the search will return -1.
You can use LINQ.
//string command = "SELECT category_id, name FROM CATEGORY ORDER BY name";
//List<string[]> list = database.Select(command, false);
// sample data...
List<string[]> list = new List<string[]> { new string[] { "aaa", "bbb" }, new string[] { "ccc", "ddd" } };
cbxCategory.Items.Clear();
foreach (string[] result in list)
{
cbxCategory.Items.Add(new ComboBoxItem(result[1], result[0]));
}
ComboBoxItem tmp = cbxCategory.Items.OfType<ComboBoxItem>().Where(x => x.ResultFirst == "bbb").FirstOrDefault();
if (tmp != null)
cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf(tmp);
ComboBoxItem class:
class ComboBoxItem
{
public string ResultFirst { get; set; }
public string ResultSecond { get; set; }
public ComboBoxItem(string first, string second)
{
ResultFirst = first;
ResultSecond = second;
}
}
Here's my simple solution
var list = comboBox1.Items.Cast<string>().ToList();
cbxCategory.SelectedIndex = list.FindIndex(c => c.StartsWith("test"));
My solution:
int? defaultID = null;
foreach (DataRow dr in dataSource.Tables["DataTableName"].Rows)
{
if ((dr["Name"] != DBNull.Value) && ((string)dr["Name"] == "Default Name"))
{
defaultID = (int)dr["ID"];
}
}
if (defaultID != null) comboBox.SelectedValue = defaultID;
I'm trying to write to a model for the first time to use in my view: the first time I write to the model I get an ArgumentOutOfRangeException.
Getting error on first write to array:
private IAdditionalQuestionsService _service;
private SelectedAdditionalQuestionAnswerModel _model;
private void InitializeController()
{
_service = GetObject<IAdditionalQuestionsService>();
//GetPageHeaderText(inst);
ViewBag.GetPageTitle = "Additional Questions";
}
[HttpGet]
public virtual ActionResult Edit()
{
Institution inst = _service.GetInstitution(State.GetInstitutionRecordId());
_model = GetObject<SelectedAdditionalQuestionAnswerModel>();
_model.AddQuestAnswModel = new List<AdditionalQuestionAnswerModel>();
GetPageConfiguration1(inst);
return View(_model);
}
AdditionalQuestionAnswerModel m = GetObject<AdditionalQuestionAnswerModel>();
int c = 0;
foreach (var x in inst.AdditionalQuestions)
{
foreach (var y in x.AdditionalQuestionAnswers)
{
// Error is happening on next line *************
_model.AddQuestAnswModel[c].QuestionText = x.QuestionText;
_model.AddQuestAnswModel[c].InstitutionId = x.InstitutionId;
_model.AddQuestAnswModel[c].AdditionalQuestionId = x.Id;
_model.AddQuestAnswModel[c].AnswerText = y.AnswerText;
_model.AddQuestAnswModel[c].IsSelected = false;
c++;
}
}
You can't use _model.AddQuestAnswModel[c] because you never added any items to your list.
Instead of that, create a new object and set its values and then add the item to your list.
Something like this:
AdditionalQuestionAnswerModel newItem = new AdditionalQuestionAnswerModel();
//set the values here to newItem
_model.AddQuestAnswModel.Add(newItem);
You're firstly instantiating your list
_model.AddQuestAnswModel = new List<AdditionalQuestionAnswerModel>();
then you try to access to the first element
_model.AddQuestAnswModel[c] // c == 0
without adding any element to the list.
Add an element before trying to access to a list by index, or more simple:
foreach (var y in x.AdditionalQuestionAnswers)
{
AdditionalQuestionAnswerModel newObj = new AdditionalQuestionAnswerModel
{
QuestionText = x.QuestionText;
InstitutionId = x.InstitutionId;
AdditionalQuestionId = x.Id;
AnswerText = y.AnswerText;
IsSelected = false;
};
_model.AddQuestAnswModel.Add(newObj);
}
Ir means that there no item in your _model.AddQuestAnswModel at the indicated postition, and from your code, I see that _model.AddQuestAnswModel has only be initiated with new List<AdditionalQuestionAnswerModel>(), so it does not contain items (unless you're doing it in the contructor).
You need to fill it like so :
_model.AddQuestAnswModel.Add(item);