Linq2Sql referring to entity column by variable creation - linq-to-sql

I have a linq2sql class with fields
WeekEnding1
WeekEnding2
WeekEnding3
WeekEnding4
I want to write some c# using the fields in a for loop.
Take this for example:
for(int i=1; i<=4; i++)
{
Msgbox(myClass.WeekEnding + i)
}
I realise that wont work but what will??
Malcolm

Unless you want to get into something with reflection, this will:
MsgBox(myClass.WeekEnding1);
MsgBox(myClass.WeekEnding2);
MsgBox(myClass.WeekEnding3);
MsgBox(myClass.WeekEnding4);
You can do what you're trying to do with reflection by putting this inside the loop:
PropertyInfo info myClass.GetType()
.GetProperty("WeekEnding" + i.ToString(),
BindingFlags.Public | BindingFlags.Instance);
MsgBox(info.GetValue(myClass, null));
But I'd recommend the first approach! The second approach will have to find the property in question on each pass through the loop, adding a considerable overhead.
In any event, your underlying data model sounds very much like it might need normalising - this is a common bad smell!

Related

New to ActionScript3, Making calculator and stuck

first time here on stackoverflow and first time scripting in flashCS6.
ill get down to it - the only lang ive done is html and a bit of css. I tried learning java, but gave up since i realised im making flash games so might as well just do AS3. Its pretty similar and not at all at the same time.
As my first original program (i did a tutorial of pong from a website before, got to know a bit about functions and event handlers[http://as3gametuts.com/2011/03/19/pong-1/]), im trying to create a calculator, and what want to know is how i can return the values from two input fields, put them into a logic calculator (say input a is 1 and input b is 2, and there are four functions, each attached to an event listener for the 4 mathematical operations, and i press addition so the calculator goes 2+1=3)
main question here, how do i get the outut text field to display the answer. In java i just used system.out.println(inputA + inputB).
Here i tried to do out.text = ( a + b) (where out is output , a is input and b is input 2)
Here is the code i have so far:
a is input 1, b is input 2
Out is output
and mul, add, sub and div are symbols containing dynamic test fields with instance names adn, sub, mul and div respectively. The symbol instances are the same as the test instances) Ex: i have a text field that says addition, its instance name is adn, then i convert it to a symbol and make its instance name adn as well.
a.text.restrict = "0-9";
b.text.restrict = "0-9";
mul.addEventListener(MouseEvent.CLICK, output);
adn.addEventListener(MouseEvent.CLICK, addition);
sub.addEventListener(MouseEvent.CLICK, subtraction);
div.addEventListener(MouseEvent.CLICK, division);
a.addEventListener(TextInput,input);
b.addEventListener(TextInput,input);
function output ():void
{
out.text=("test to see if output works")
}
function input (e:TextInput)
{
}
function multiplication (e:MouseEvent)
{
}
function addition (e:MouseEvent)
{
}
function subtraction (e:MouseEvent)
{
}
function division (e:MouseEvent)
{
}
thanks guys, and cheers! Also, ill appreciate if anyone can link me to a good video or text tutorial (series) for AS3 introduction. My main focus is to be making PC games and not apps, so keep that in mind.
Check This Out
Also, don't forget to convert value to string, that may be neccessary:
out.text = String(a + b);
Since a text field will give you the input typecast as a string you will need to type cast them to type Number or type int before you can do any kind of math function on them.
And if you want to create a more complex calculator I would suggest you read up on the Math class
function subtraction (e:MouseEvent)
{
var result:Number = Number(a.text) - Number(b.text)
out.text = String(result)
}

Can you help me make more OOP abstraction with this code?

This code is not java code, and I'm not getting any answer from ActionScript developers. So I tagged it with java, but Action Script is similar to java and this an OOP question.
I'm using Grid Data and I want to accomplish this following task:
Method 1: I want to multiply each row Row1num1 * Row1num2 and so on,
var Row1num1:String;
var Row2num2:String;
var Row2num1:String;
var Row2num2:String;
var Row3num1:String;
var Row3num2:String;
var event1:Object={num1:Row1num1,num2:Row1num2};
var event2:Object={num1:Row2num1,num2:Row2num2};
var event3:Object={num1:Row3num1,num2:Row3num2};
then add them to a dataGrid
dataGrid.columns =["num1","num2"];
dataGrid.addItem(event1);
dataGrid.addItem(event2);
dataGrid.addItem(event3);
but by using this method, if I have 20 rows, I will have a lot of variables, obviously it's bad.
method 2: In this method creating Grid Data rows at runtime and multiply them.
//button to add rowGrid
dd.addEventListener(MouseEvent.CLICK,ddd);
var numm:String="34";
function ddd(evt:MouseEvent):void
{
var event4:Object={num1:Rownum1,num2:Rownum2};
dataGrid.addItem(event4);
}
but when I use this method, I have a hard time accessing each row data and multiply them.
This example because I'm creating GPA calculator and I want to take each row credit Hours and multiply them with the scale value at the same row, first method is bad because there's not abstraction .
The second method what I'm hoping to work ,because I want user to add row depend on their number of courses.
I hope my English is not bad.
I hope my question don't get vote down, and by reading this question can you determine what I'm missing so I can learn it .
And is there any tutorial I can use to solve my problem?
I'm just addressing your first method for now, but it almost seems at though you want an array of some sort.
Here's a link on how to use Actionscript arrays.
If you need more dimensions, you can make an array of arrays. This will help you cut down on the number of variables.
I hope I correctly understood your question. I'll give it a go either way...
So, one of the best things about actionscript in comparison to most other strongly-typed Object-Oriented languages is how easy reflection is (probably thanks to its javascript origins).
That being said, what you can do is simply create an array using a "for" loop. What I am assuming is that the variables row1Num1 row2Num2 and so on already exist in your class. Otherwise, obviously it would be much more efficient to store them in an array and simply read from it into a new array. Anyhow, the code should look something like this:
method 1:
var eventsArr:Array = [];
for(var i:int = 1; this["row" + i + "Num1"] != undefined /*or i<=length*/; i++){
eventsArr.push({num1:this["row" + i + "Num1"], num2:this["row" + i + "Num2"]});
}
for(var j:int = 0; j < eventsArr.length; j++){
dataGrid.addItem(eventsArr[j]);
}
method 2:
dd.addEventListener(MouseEvent.CLICK,ddd);
var numm:String="34"; //I am assuming this refers to the row number you wanted to add.
function ddd(evt:MouseEvent):void
{
var event4:Object={num1:this["row" + numm + "Num1"],num2:this["row" + numm + "Num2"]};
eventsArr.push(event4);
dataGrid.addItem(event4);
}
Hope that helps.

Possible multiple enumeration of IEnumerable when counting and skipping

I'm preparing data for a datatable in Linq2Sql
This code highlights as a 'Possible multiple enumeration of IEnumerable' (in Resharper)
// filtered is an IEnumerable or an IQueryable
var total = filtered.Count();
var displayed = filtered
.Skip(param.iDisplayStart)
.Take(param.iDisplayLength).ToList();
And I am 100% sure Resharper is right.
How do I rewrite this to avoid the warning
To clarify, I get that I can put a ToList on the end of filtered to only do one query to the Database eg.
var filteredAndRun = filtered.ToList();
var total = filteredAndRun.Count();
var displayed = filteredAndRun
.Skip(param.iDisplayStart)
.Take(param.iDisplayLength).ToList();
but this brings back a ton more data than I want to transport over the network.
I'm expecting that I can't have my cake and eat it too. :(
It sounds like you're more concerned with multiple enumeration of IQueryable<T> rather than IEnumerable<T>.
However, in your case, it doesn't matter.
The Count call should translate to a simple and very fast SQL count query. It's only the second query that actually brings back any records.
If it is an IEnumerable<T> then the data is in memory and it'll be super fast in any case.
I'd keep your code exactly the same as it is and only worry about performance tuning when you discover you have a significant performance issue. :-)
You could also do something like
count = 0;
displayed = new List();
iDisplayStop = param.iDisplayStart + param.iDisplayLength;
foreach (element in filteredAndRun) {
++count;
if ((count < param.iDisplayStart) || (count > iDisplayStop))
continue;
displayed.Add(element);
}
That's pseudocode, obviously, and I might be off-by-one in the edge conditions, but that algorithm gets you the count with only a single iteration and you have the list of displayed items only at the end.

Custom sorting function bottleneck

I am trying to sort big array using actionscript 3.
The problem is that i have to use custom sorting function which is painfully slow and leads to flash plugin crash.
Below is a sample code for custom function used to sort array by length of its members:
private function sortByLength():int {
var x:int = arguments[0].length;
var y:int = arguments[1].length;
if (x > y){
return 1;
}else if (x < y){
return -1;
}else{
return 0;
}
}
Which is called like this:
var txt:Array = ["abcde","ab","abc","a"];
txt.sort(sortByLength);
Please advise me how can this be done faster ?
How to change application logic to avoid Flash plugin crashes during sorting ?
try to use strong typing whenever possible, here tell your function that you are waiting two strings.
you could rewrite your function in two way one fastest than the other if you know that all your element are not null:
function sortByLength(a:String, b:String):int {
return a.length-b.length // fastest way not comparison
}
and if you can have null check for it (this one will put null in front of all element):
function sortByLengthWithNull(a:String, b:String):int {
if (a==null) return -1
if (b==null) return 1
return a.length-b.length
}
If you need super-fast sorting, then it might be worthwhile not using an array at all and instead using a linked-list. There are different advantages to each. Primarily, with a linked-list, index-access is slow, while iterating through the list is fast, and linked-lists are not native to AS3 so you'll have to roll your own.
On the upside, you may well be able to use some of Polygonal Labs' code: http://lab.polygonal.de/as3ds/.
Sorting is very, very fast for nearly-sorted data with a linked list, as this article discusses: http://lab.polygonal.de/2007/11/26/data-structures-more-on-linked-lists/.
This solution gives you lots more work, but will eventually give you lots more sort-speed too.
Hope this helps.
-- additional --
I noticed your question in the comments of another answer about "One question however is unanswered - how to perform greedy computations in Flash without hanging it?"
For this, essentially the answer is to break your computation over multiple frames, something like this:
public function sort():void
{
addEventListener(Event.ENTER_FRAME, iterateSort);
}
private function iterateSort():void
{
var time:int = getTimer() + TARGET_MILLISECONDS_PER_FRAME;
var isFinished:Boolean = false;
while (!isFinished && getTimer() < time)
isFinished = continueSort();
if (isFinished)
removeEventListener(Event.ENTER_FRAME, iterateSort);
}
function continueSort():Boolean
{
... implement an 'atom of sort' here, whatever that means ...
}
sortByLength should have two parameters, shouldn't it? I guess that's what you mean by the arguments array...
This looks fine to me, unless arguments is not a local variable, but instead a member variable, and you're just looking at its [0] and [1] elements on each function call. That would at least produce undesired results.

How to sort var length ids (composite string + numeric)?

I have a MySQL database whose keys are of this type:
A_10
A_10A
A_10B
A_101
QAb801
QAc5
QAc25
QAd2993
I would like them to sort first by the alpha portion, then by the numeric portion, just like above. I would like this to be the default sorting of this column.
1) how can I sort as specified above, i.e. write a MySQL function?
2) how can I set this column to use the sorting routine by default?
some constraints that might be helpful: the numeric portion of my ID's never exceeds 100,000. I use this fact in some javascript code to convert my ID's to strings concatenating the non-numeric portion with the (number + 1,000,000). (At the time I had not noticed the variations/subparts as above such as A_10A, A_10B, so I'll have to revamp that part of my code.)
The best way to achieve what you want is to store each part in its own column, and I would strongly recommend to change table structure. If it's impossible, you can try the following:
Create 3 UDFs which returns prefix, numeric part, and postfix of your string. For a better performance they should be native (Mysql, as any other RDMS, is not really good in complex string parsing). Then you can call these functions in ORDER BY clause or in trigger body which validates your column. In any case, it will work slower than if you create 3 columns.
No simple answer that I know of. I had something similar a while back but had to use jQuery to sort it. So what I did was first get the output into an javascript array. Then you may want to insert a zero padding to your numbers. Separate the Alpha from Nummerics using a regex, then reassemble the array:
var zarr = new Array();
for(var i=0; i<val.length; i++){
var chunk = val[i].match(/(\d+|[^\d]+)/g).join(',');
var chunks = chunk.split(",");
for(var s=0; s<chunks.length; s++){
if(isNaN(chunks[s]) == true)
zarr.push(chunks[s]);
else
zarr.push(zeroPad(chunks[s], 5));
}
}
function zeroPad(num,count){
var numZeropad = num + '';
while(numZeropad.length < count) {
numZeropad = "0" + numZeropad;
}
return numZeropad;
}
You'll end up with an array like this:
A_00100
QAb00801
QAc00005
QAc00025
QAd02993
Then you can do a natural sort. I know you may want to do it through straight MySQL but I am not to sure if it does natural sorting.
Good luck!