Reputation: 23833
All, I want to create an object array foo[]
, where the constructor for Foo
is
public Foo(string name, string discription){}
I have a database object which has a structure (not incuding stored procedures, functions or views for simplicity) like
public class Database
{
public string name { get; set; }
public string filename { get; set; }
public List<Table> tables { get; set; }
public Database(string name, string filename)
{
this.name = name;
this.filename = filename;
}
}
protected internal class Table
{
public string name { get; set; }
public List<Column> columns { get; set;}
public Table(string name, List<Column> columns)
{
this.name = name;
this.columns = columns;
}
}
protected internal class Column
{
public string name { get; set; }
public string type { get; set; }
public Column(string name, string type, int maxLength,
bool isNullable)
{
this.name = name;
this.type = type;
}
}
I would like to know the quickest way to add Column
and Table
information to the Foo[]
object array?
Clearly I can do
List<Foo> fooList = new List<Foo>();
foreach (Table t in database.tables)
{
fooList.Add(new Foo(t.Name, "Some Description"));
foreach (Column c in t.columns)
fooList.Add(new Foo(c.Name, "Some Description"));
}
Foo[] fooArr = fooList.ToArray<Foo>();
But is there a quicker way? Clearly LINQ is likely to be slower for a query that does a simalar operation, but I care allot about speed here so any advice would be appreciated. Perhaps the use of a HashSet would be the way to go as there will not be duplicate entries...
Thanks for your time.
Upvotes: 0
Views: 245
Reputation: 138
I would say change your foreach loop to for loop, as discussed here In .NET, which loop runs faster, 'for' or 'foreach'? Datastructure wise, you do need mutable structure, unless you know exactly how many records you will be inserting into fooList, then you can use Array instead of list. According to the answer of the foreach vs for-loop question, assuming it's correct, for loops on List are a bit more than 2 times cheaper than foreach loops on List, and Looping on array is around 2 times cheaper than looping on List.
So 2 improvement would be:
change foreach to for
use linq to compute the length for the array as per @Tim Schmelter, and change List to Array
Upvotes: 2
Reputation: 460138
You could initialize the array with the correct size and only use it without a backing list:
int size = db.tables.Sum(t => t.columns.Count + 1);
Foo[] fooArr = new Foo[size];
int currentSize = 0;
foreach (var tbl in db.tables)
{
fooArr[currentSize++] = new Foo(tbl.Name, "Some Discription");
foreach(var c in tbl.columns)
fooArr[currentSize++] = new Foo(c.Name, "Some Discription");
}
Upvotes: 2