Reputation: 6878
I have a linq query and I think I am doing somthing with Lambdas. (don't really know what it's called, I am very new to this)
This is my code:
private static readonly Func<customer, string>[] _searches;
static Main()
{
_searches = new Func<customer, string>[]
{
(c) => customer.city,
(c) => customer.state,
(c) => customer.country
};
}
protected virtual void SearchBox_TextChanged(object sender, EventArgs e)
{
CustomerContext context = new CustomerContext();
var search = _searches[ComboBox1.SelectedValue];
IQueryable<customer> customers = from x in context.customers
where search(x).Contains(SearchBox.Text)
select x;
loadList(customers);
}
Now my problem is that I get an error at customer.city
, customer.state
and so on.
The error is:
An object reference is required for the for the non-static field, method or property 'customer.city' Cannot access non-static property 'city' in static context
I have tried making the field static
but that breaks the code, when I try to instantiate the field it breaks aswel. Or atleast, when I change customer.city
to new customer().city
I thought that's called instantiating, but I am not 100% sure.
So, how do I solve this problem?
EDIT:
private void loadList(IQueryable<customer> customers)
{
ListView.Items.Clear();
foreach (var customer in customers)
{
ListViewItem item = new ListViewItem(customer.customerNumber.ToString());
item.SubItems.Add(customer.customerName);
item.SubItems.Add(customer.contactFirstName);
item.SubItems.Add(customer.contactLastName);
item.SubItems.Add(customer.phone);
item.SubItems.Add(customer.addressLine1);
item.SubItems.Add(customer.addressLine2);
item.SubItems.Add(customer.city);
item.SubItems.Add(customer.state);
item.SubItems.Add(customer.postalCode);
item.SubItems.Add(customer.country);
item.SubItems.Add(customer.salesRepEmployeeNumber.ToString());
item.SubItems.Add(customer.creditLimit.ToString());
ListView.Items.AddRange(new ListViewItem[] { item });
}
}
Upvotes: 1
Views: 329
Reputation: 216293
Func<customer, string>[] _searches;
means that you declare an array of functions that return a string and receive an instance variable of type customer
but when you write
(c) => customer.city,
here you are not using the instance passed (c) but you access directly the class customer by its name and this works only for properties, methods or fields that are declared as static
Instead you just need to use the customer instance that has been passed to you at the where search(x) where x is the instance of a customer extracted by your line from x in context.customers and you receive in the Func as the variable named c
(c) => c.city,
Upvotes: 2