简体   繁体   中英

How to declare a global variable to be used on a C# expression

I´m doing this :

protected void btn_Click(object sender, EventArgs e){

var myQuery = from tab1 in Table
              where myConditions
              select tab1 ;

After that, I´m filtering with user selected choices :

myQuery.Where(x => x.someField == someChoice);

It´s working fine. But I would like to declare the "myQuery" with global escope.

How should I do that ? I´m trying to put the line below inside the class and outside the method, but I don´t know what type should I use :

private someTypeThatIdontKnow myQuery;

TIA.

The sneaky way to do this is to make it:

this.myQuery = ...

then position the caret at the myQuery (which will have a red squiggly, indicating a problem), and press ctrl + . , and select the IDE's offer to generate a field:

在此处输入图片说明

This generates a field of the correct type:

在此处输入图片说明

Now just move the query itself into where-ever you need it (presumably a constructor), after MyTable has been set.

If you hover your mouse over the var keyword it will tell you what type it is.

You can then use that to define a member for the class to hold the result.

You can use the var keyword and obtain the type and then declare the variable of that type.

Or, if from some reason you do not want to do it that way, you could use a dynamic type, but I would advise against that.

The best solution would be to let the compiler infer the type with the var keyword and then use that type explicitly as the class member (the "global variable" as you referred to it).

LINQ查询返回某种IEnumerable,所以我相信它将

private IEnumerable<TypeOfObjectInYourCollection> myQuery;

Use IQueryable<TableEntity> , where TableEntity is the type of the objects in your Table DbSet .

It may also be an IEnumerable<TableEntity> , depending on whether you run your query against a database or some in-memory collection.

You can also see which type to use by hovering your mouse over myQuery .

The type will be an IQueryable of type tab1 .

Assuming you eventually call ToList() to run the query, you'll end up with a List<tab1> . So you can declare your global variable as that type.

I'm assuming tab1 is an object that's available for you to have a list of.

List<tab1> result = new List<tab1>();

protected void btn_Click(object sender, EventArgs e)
{
    var myQuery = from tab1 in Table
                  where myConditions
                  select tab1;

    myQuery.Where(x => x.someField == someChoice);

    result = myQuery.ToList();
}

试试EnumerableRowCollection

 private EnumerableRowCollection query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM