質問

Basically I have a function as below that allow user login when execute the application:

public void login(){
    //Call StoredProc get a list of records 
    //and add the results into a list<T> SPList

    var tempList = SPList.Where(x=>x.Status==1);
    int counter = tempList.Count();

    //What is the number of counter?
}

Now when user first run the application, login function will be executed and tempList.Count() is expected to be 2.

When user run the same method login() again, the tempList.Count() is now becoming 4??

BUT, if user kill the apps and restart it, tempList.Count() will then return 2 again?

Isn't that keyword VAR will refresh and return 2 everytime? Why is it holding the old data and expanding instead of refreshing?

役に立ちましたか?

解決

I guess you don't understand what var does. With var the compiler tries to understand what type is returned from your method.

Your problem is that you keep a list in memory, where you add things, and thus the count will get updated. At restart, the list is empty again, so you will start with 0.

他のヒント

This has nothing to do with 'var'. Var is just a feature which allows you to not have to type the type when declaring a variable.

It has more to do with the inner-workings of LINQ. You should understand that your variable tempList is not holding a List or Collection, but rather an expression. Each time you do an operation on 'tempList' (like calling Count() or iterating over it), the expression will be evaluated again.

this:

var tempList = SPList.Where(x=>x.Status==1);
int counter = tempList.Count();

will behave totally different than this:

var tempList = SPList.Where(x=>x.Status==1).ToList();
int counter = tempList.Count();

In the second code-sample, the variable 'tempList' really contains a List, whereas in the first code-sample, the variable tempList contains an expression.

When you add a new object to SPList, and call Count() on tempList again, the new item will be included in the count in the first code-example, whereas in the second code-sample it will not be included. (Since in the 2nd sample, tempList is now a separete list, whereas in the first sample, the expression that counts the items in SPList is executed again).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top