Laki
Laki

Reputation: 99

Passing var value to another class

I have this example of code which defines local variable:

private void btnFindName_Click(object sender, EventArgs e)
{
    var query = db.Users.AsQueryable();
    query = query.Where(x => x.name == txtName);
    userBindingSource.DataSource = query.ToList();
}

The next method sorts all users from my binding source:

private void sortToolStripMenuItem_Click(object sender, EventArgs e)
{
    userBindingSource.DataSource = db.Users.OrderBy(x => x.name).ToList();
}  

I would like to rewrite this method in order to sort only users obtained in the first method as 'var query' (not all of them). My idea is to have something like this:

userBindingSource.DataSource = query.OrderBy(x => x.name).ToList();

How can I pass the value of query from the first method to the second one in this case?

Thank you.

Upvotes: 0

Views: 62

Answers (1)

Jcl
Jcl

Reputation: 28272

Don't make it local:

private IQueryable<User> _query;

private void btnFindName_Click(object sender, EventArgs e)
{
    _query = db.Users.AsQueryable();
    _query = _query.Where(x => x.name == txtName);
    userBindingSource.DataSource = _query.ToList();
}

private void sortToolStripMenuItem_Click(object sender, EventArgs e)
{
    userBindingSource.DataSource = _query.OrderBy(x => x.name).ToList();
}  

Definitely not the best way to do what you are aiming at, but this answers your specific question

Upvotes: 1

Related Questions