tags:

views:

218

answers:

2

Hello Friends,

I been trying to write the following code in expression based way but not sure how can i do that assignment to the object after comparison. Any help would be highly appreciated.

var pcs = from a in collection
      group a by a.TotType
      into g
      select new
      {
          TType = g.Key,
          SColl = g.Select(r => r)
     };

for (int i = 0; i < processResult.PAndLReport.BreakdownTotTypeCollection.Count; i++)
{
  foreach (var ttypes in pcs)
  {
    if (processResult.PAndLReport.BreakdownTotTypeCollection[i].TotType == ttypes.TType)
    {
      BreakdownCollection coll = new BreakdownCollection();
      foreach (var item1 in ttypes.SColl)
       {
         coll.Add(item1);
       }

      processResult.PAndLReport.BreakdownTotTypeCollection[i].BreakdownCollection = coll;
     }
  }
}
+1  A: 

So - the code works, but it's very verbose.

Here's a stab at reducing the code. I've made some assumptions (this code doesn't do exactly the same assignments as the other code), but it might be close to what you want.

var pcs = collection.ToLookup(a => a.TotType);

foreach(var bttcoll in processResult
    .PAndLReport
    .BreakdownTotTypeCollection)
{
  var items = pcs[bttcoll.ToTType];
    //do you have a constructor that takes an IEnumerable<Item> ?
  bttcoll.BreakdownCollection = new BreakdownCollection(items)
}

In general, you should avoid changing object state inside of a linq query. Linq is from the functional programming mindset, where state never changes (instead, new objects are created with the needed state).

David B
A: 

If the answer David B gives works, that is great, but DO NOT use it in your code. The first one (presumably) works and is much easier for the next guy to comprehend.

Some things to think about:

  1. If your code will be used for a long time then much more time will be spent maintaining it then in the original writing of it. You will have to modify the behavior shortly after you have forgotten exactly what it was you were doing. Make it easier on yourself.
  2. If your code will not be used for long, then you have spent more time in tweaking the style and flow then will be recovered.
  3. There is no speed benefit in using expression style Linq over declarative style. The compiler will convert the code for you and in most cases will be just as efficient as what you could write yourself.
Kirk