Is that a shorter way assigning properties with LINQ Query Syntax?

45 views Asked by At

Say I have a list of an object with 30 properties (eg: Items)

If I am using LINQ Query-Syntax to Join another object (eg: Store), it seems inevitable that i have to re-assign every property from the Item, right?

For example:

    var temp = from a in items
               join b in stores on a.storeKey = b.storeKey into b2
               from c in b2.DefaultIfEmpty()
               select new ItemViewModel()
               {
                  p1 = a.p1,
                  p2 = a.p2,
                  ....
                  p30 = a.p2, //re-assign 30 times (T.T)

                  storeInfo1 = c.storeInfo1 //all i want is 1 or 2 additional info from store
               }
2

There are 2 answers

0
Peter B On BEST ANSWER

You could use a library such as AutoMapper. For property names that are the same between a and ItemViewModel it can do the mapping for you using reflection, for properties with different names you can define a manual mapping, and for properties coming from the other objects (b and c) you can use a helper.

Something like this:

var temp = from a in items
           join b in stores on a.storeKey = b.storeKey into b2
           from c in b2.DefaultIfEmpty()
           select CreateModelFrom(a, b, c);

public ItemViewModel CreateModelFrom(ObjA a, ObjB b, ObjC c)
{
    var model = Mapper.Map<ObjA, ItemViewModel>();
    model.xxx = b.xxx;
    model.storeInfo1 = c.storeInfo1;
    return model;
}
1
ManishM On

Seeing the requirement I think you should change your class structure. Their are two ways

  1. ItemViewModel should be derived from same class as of items or
  2. it should a property inside in it

I am writing the second way

class Item
{
     string p1;
     ......
}

class ItemViewModel
{
     string p1;
     ......
     string storeInfo1;
     Item item;

     ItemViewModel(Item item, string storeInfo)
     {
        this.item= item;
        this.storeInfo1 = storeInfo;
     }
}

var temp = from a in items
           join b in stores on a.storeKey = b.storeKey into b2
           from c in b2.DefaultIfEmpty()
           select new ItemViewModel(a, c.storeInfo1);