Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ In Line Property Update During Join

Tags:

c#

linq

I have two obects, A & B for this discussion. I can join these objects (tables) via a common relationship or foreign key. I am using linq to do this join and I only want to return ObjectA in my result set; however, I would like to update a property of ObejctA with data from ObjectB during the join so that the ObjectAs I get out of my LINQ query are "slightly" different from their original state in the storage medium of choice.

Here is my query, you can see that I would just like to be able to do something like objectA.SomeProperty = objectB.AValueIWantBadly

I know I could do a new in my select and spin up new OBjectAs, but I would like to avoid that if possible and simply update a field.

return from objectA in GetObjectAs()
   join objectB in GetObjectBs()
           on objectA.Id equals objectB.AId
           // update object A with object B data before selecting it
   select objectA;
like image 348
JPrescottSanders Avatar asked Apr 02 '09 12:04

JPrescottSanders


1 Answers

Add an update method to your ClassA

class ClassA {
  public ClassA UpdateWithB(ClassB objectB) {
    // Do the update
    return this;
  }
}

then use

return from objectA in GetObjectAs()
   join objectB in GetObjectBs()
           on objectA.Id equals objectB.AId
           // update object A with object B data before selecting it
   select objectA.UpdateWithB(objectB);

EDIT:

Or use a local lambda function like:

Func<ClassA, ClassB, ClassA> f = ((a,b)=> { a.DoSomethingWithB(b); return a;});
return from objectA in GetObjectAs()
       join objectB in GetObjectBs()
       on objectA.Id equals objectB.AId
       select f(objectA , objectA );
like image 124
MartinStettner Avatar answered Sep 22 '22 16:09

MartinStettner