Friday, May 4, 2018

Linq extension

                        
Group by using datatable
var ImportgroupPONo = dt.AsEnumerable() //excel sum qty by pono
.Where(p => p.Field("PONo") == pono)
.GroupBy(p => p.Field("PONo"))
.Select(grp => new
{
PONo = grp.Key,
SumBuyQTY = grp.Sum(n => int.Parse(n.Field("BuyQTY" ?? "0")))
});

var query = cust.GroupBy(p => p.Customer)
                .Select(g => new { CKey = g.Key, Count = g.Count() });
You can also simplify this into a single call to this GroupBy overload though:
var query = cust.GroupBy(p => p.Customer,
                         (key, g) => new { CKey = key, Count = g.Count() });
Note that I've changed the name of the lambda expression's parameter name for the second line to g - I believe that gives more of a clue that you're really looking at a group rather than a single entity.
I've also moved the dot onto the second line in the form that still uses Select - I find this makes the query easier to read; I usually line up the dots, e.g.
var query = foo.Where(...)
               .OrderBy(...)
               .GroupBy(...)
               .Select(...)
example:

int cntOpenCR = objectSpace.GetObjectsCount(typeof(ChangeRequest),CriteriaOperator.Parse(string.Format("PONo == '{0}' and Status < 5", pono)));

No comments: