1

I have a LINQ statement which creates a number of items

From x in datasource
   select (Customer) new BusinessCustomer(x.SomeThing)

I need to set the BusinessCustomer.OnTapped event handler.

Can this be done in the LINQ statement?

Ian Vink
  • 66,960
  • 104
  • 341
  • 555
  • http://stackoverflow.com/questions/807797/linq-select-an-object-and-change-some-properties-without-creating-a-new-object – Davide Piras Sep 20 '11 at 23:19
  • 1
    No it can't and shouldn't. Write a loop. Add helper methods. Whatever. LINQ should be used for performing queries, not modifying things. – Jeff Mercado Sep 20 '11 at 23:37

1 Answers1

2

If you can modify the BusinessCustomer class, you could add a constructor that accepts a handler delegate for the OnTapped event.

If you can't or don't want to modify BusinessCustomer to do this, you could use a helper method, which would also allow you to eliminate the cast.

private Customer CreateBusinessCustomer(Thing thing, EventHandler tapHandler)
{
    var customer = new BusinessCustomer(thing);
    customer.OnTapped = tapHandler;
    return customer;
}

private void Customer_OnTapped(object sender, EventArgs e)
{
    // do something
}

Now your query looks like:

from x in datasource
select CreateBusinessCustomer(x.SomeThing, Customer_OnTapped)
Jay
  • 56,361
  • 10
  • 99
  • 123