naming objects using for loop - for-loop

is there a way to name a series of objects like so:
for (i=0; i<numberOfObjectsDesired; i++;) {
Object ("thisone"+i);
thisone+i = new Object();
}
such that
thisone0, thisone1, thisone2, thisone3, ... etc are all unique instances of Objects

Sure, it's called an array:
var thisone = new object[numberOfObjectsDesired];
for (i=0; i<numberOfObjectsDesired; i++;) {
Object ("thisone"+i);
thisone[i] = new Object();
}
Just note that you have to refer to your instances as thisone[0], thisone[1], etc. instead of thisone0, thisone1, ...

Related

Convert an object into list or array MVC

I have an MVC grid control that is passing back the collection to my controller as an object.
The object is an ArrayList of the rows from the grid and each row is a List that represents an instance of a class called lineitem that is part of a parent record class.
I am trying to load the object into the class by looping through the object array, create an instance of my lineitem class, and then add it to my parent record class parent.AddItem(lineitem). I originally had it created as follows
var items = requestData.ExtraRequestData["Items"];
However As I determined, it was an ArrayList I changed that to
List<string> mylist;
ArrayList items = (ArrayList)requestData.ExtraRequestData["Items"];
mylist = items.Cast<string>().ToList();
I am trying to convert the ArrayList into a List so I can loop through it and load it into my class.
Model.Parent parent = new Model.Parent();
Model.LineItem lineitem = new Model.LineItem();
for (int I = 0; I < mylist.length; I++){
lineitem.a = item.a,
lineitem.b = item.b
parent.AddItem(lineitem)
}
I am getting the following error on the line where I set mylist = items:
{"Unable to cast object of type 'System.Collections.Hashtable' to type 'System.String'."}
What am I missing to convert this so I can load it into my class?
Since each item in the ArrayList was a hashtable, I ended up looping through it as follows:
ParentClass ReconHdr = new ParentClass();
foreach (System.Collections.Hashtable o in items)
{
//lineItem.LineSeq = Convert.ToInt32(item.Value);
ArrayList list = new ArrayList(o.Values);
ChildClass lineItem = new ChildClass();
lineItem.StmntDocNum = list[0].ToString();
lineItem.PrtlAmt = Convert.ToDouble(list[1]);
lineItem.GLAcctCode = list[2].ToString();
lineItem.LineSeq = Convert.ToInt32(list[3]);
lineItem.ClinicID = Convert.ToInt32(list[4]);
lineItem.PrtlTranDate = Convert.ToDateTime(list[5]);
lineItem.StmntTranDate = Convert.ToDateTime(list[6]);
lineItem.PrtlFinRptDate = Convert.ToDateTime(list[7]);
lineItem.StmntEndDate = Convert.ToDateTime(list[8]);
lineItem.StmntAmt = Convert.ToDouble(list[9]);
lineItem.PrtlDocNum = list[10].ToString();
lineItem.PrtlUniqueID = list[11].ToString();
ReconHdr.AddItem(lineItem);
}

Name of all the children objects in a three.js object

i want to get the var name of all the children objects in a three.js object and then store them in an array.
object has a property .children but this gets an array of all the data not just an array of the objects variable names
this is what i have tried but comes up empty
var arrayHead = headGroup.children;
var testarray =[];
for (var i = 0; i < testarray.length; i++) {
testarray.push(arrayHead[i].name);
}
if arrayHead is of type Object3D()
var testarray = [];
arrayHead.traverse ( function (child) {
testarray.push( child.name );
} );

Dynamically choose which properties to get using Linq

I have an MVC application with a dynamic table on one of the pages, which the users defines how many columns the table has, the columns order and where to get the data from for each field.
I have written some very bad code in order to keep it dynamic and now I would like it to be more efficient.
My problem is that I don't know how to define the columns I should get back into my IEnumerable on runtime. My main issue is that I don't know how many columns I might have.
I have a reference to a class which gets the field's text. I also have a dictionary of each field's order with the exact property It should get the data from.
My code should look something like that:
var docsRes3 = from d in docs
select new[]
{
for (int i=0; i<numOfCols; i++)
{
gen.getFieldText(d, res.FieldSourceDic[i]);
}
};
where:
docs = List from which I would like to get only specific fields
res.FieldSourceDic = Dictionary in which the key is the order of the column and the value is the property
gen.getFieldText = The function which gets the entity and the property and returns the value
Obviously, it doesn't work.
I also tried
StringBuilder fieldsSB = new StringBuilder();
for (int i = 0; i < numOfCols; i++)
{
string field = "d." + res.FieldSourceDic[i] + ".ToString()";
if (!string.IsNullOrEmpty(fieldsSB.ToString()))
{
fieldsSB.Append(",");
}
fieldsSB.Append(field);
}
var docsRes2 = from d in docs
select new[] { fieldsSB.ToString() };
It also didn't work.
The only thing that worked for me so far was:
List<string[]> docsRes = new List<string[]>();
foreach (NewOriginDocumentManagment d in docs)
{
string[] row = new string[numOfCols];
for (int i = 0; i < numOfCols; i++)
{
row[i] = gen.getFieldText(d, res.FieldSourceDic[i]);
}
docsRes.Add(row);
}
Any idea how can I pass the linq the list of fields and it'll cut the needed data out of it efficiently?
Thanks, Hoe I was clear about what I need....
Try following:
var docsRes3 = from d in docs
select (
from k in res.FieldSourceDic.Keys.Take(numOfCols)
select gen.getFieldText(d, res.FieldSourceDic[k]));
I got my answer with some help from the following link:
http://www.codeproject.com/Questions/141367/Dynamic-Columns-from-List-using-LINQ
First I created a string array of all properties:
//Creats a string of all properties as defined in the XML
//Columns order must be started at 0. No skips are allowed
StringBuilder fieldsSB = new StringBuilder();
for (int i = 0; i < numOfCols; i++)
{
string field = res.FieldSourceDic[i];
if (!string.IsNullOrEmpty(fieldsSB.ToString()))
{
fieldsSB.Append(",");
}
fieldsSB.Append(field);
}
var cols = fieldsSB.ToString().Split(',');
//Gets the data for each row dynamically
var docsRes = docs.Select(d => GetProps(d, cols));
than I created the GetProps function, which is using my own function as described in the question:
private static dynamic GetProps(object d, IEnumerable<string> props)
{
if (d == null)
{
return null;
}
DynamicGridGenerator gen = new DynamicGridGenerator();
List<string> res = new List<string>();
foreach (var p in props)
{
res.Add(gen.getFieldText(d, p));
}
return res;
}

What is the faster way to access a DataTable/DataRowsCollection?

I have a datatable with 100,000+ DataRow. Which method is faster to access the collection?
Is there any faster way to process the rows collection ?
Method 1:
var rows= dsDataSet.Tables["dtTableName"].Rows;
int rowCount = dsDataSet.Tables["dtTableName"].Rows.Count;
for (int c = 0; c < rowCount; c++)
{
var theRow = rows[c];
//process the dataRow
}
Method 2:
for (int c = 0; c < dsDataSet.Tables["dtTableName"].Rows.Count; c++)
{
var theRow = dsDataSet.Tables["dtTableName"].Rows[c];
//process the dataRow
}
It is worth noting the most direct way to access cells is via the DataColumn indexer; the data is actually stored in the columns, not the rows (no: really).
So something like:
var table = dataSet.Tables["dtTableName"];
// HERE: fetch the DataColumn of those you need, for example:
var idCol = table.Columns["Id"];
var nameCol = table.Columns["Name"];
// now loop
foreach(DataRow row in table.Rows)
{
var id = (int)row[idCol];
var name = (string)row[nameCol];
// ...
}
However, frankly if you want the best performance, I would start by saying "don't use DataSet / DataTable". That is actually a very complicated model designed to be all kinds of flexible, with change tracking, rule enforcement, etc. If you want fast, I'd use a POCO and something like "dapper", for example:
public class Foo {
public int Id {get;set;}
public string Name {get;set;}
}
...
string region = "North";
foreach(var row in conn.Query<Foo>("select * from [Foo] where Region = #region",
new { region })) // <=== simple but correct parameterisation
{
// TODO: do something with row.Id and row.Name, which are direct
// properties of the Foo row returned
var id = row.Id;
var name = row.Name;
// ...
}
or even skip the type via dynamic:
string region = "North";
foreach(var row in conn.Query("select * from [Foo] where Region = #region",
new { region })) // ^^^ note no <Foo> here
{
// here "row" is dynamic, but still works; not quite as direct as a
// POCO object, though
int id = row.Id; // <=== note we can't use `var` here or the
string name = row.Name; // variables would themselves be "dynamic"
// ...
}

linq select from database where ID in an ArrayList

I have an array-list that contains some UserID.
I need a query like this:
vat tmp= users.select(a=> a.UserID in (arraylist));
what can I do?
If it's actually in an ArrayList, you should create a List<T> or array first. Then you can use Contains:
// Use the appropriate type, of course.
var ids = arraylist.Cast<string>().ToList();
var tmp = users.Select(a => ids.Contains(a.UserID));
While using Contains on the plain ArrayList may well compile, I would expect it to fail at execution time, assuming users is an IQueryable<>.
List<long> list =new List<long>();
var selected = from n in users where list.Contains(n.ID) select n ;
OR
var selected = users.Where(a=> list.Contains(a.ID)).ToList();
This is the solution I used.
public static IEnumerable<SettingModel> GetSettingBySettingKeys(params string[] settingKey)
{
using (var db = new BoxCoreModelEntities())
{
foreach (var key in settingKey)
{
var key1 = key;
yield return Map(db.Settings.Where(s => s.SettingKey == key1).First());
}
}
}

Resources