1

I am new to LINQ so apologises upfront

I have the following Linq query :-

var OrdersByBranches =
    from a in AllOrders
    join b in AllBranchKeys
        on a.BranchKey equals b.BranchKey
    orderby a.Date
    group a by new { a.Date, a.paymentMethod } into BranchOrderGrouped
    select new
    {
        BranchOrderGrouped.Key.Date,
        CurrencyAmount = BranchOrderGrouped.Sum(a =>
        a.CurrencyAmount),
        BranchOrderGrouped.Key.paymentMethod
    };

I need to include a where clause in the above query ... only if a variable called BranchKeySelected is ""

I have tried using an If Else statement and have the same above query duplicated with one containing a where clause and one NOT. ...But When I do this .. then OrdersByBranches is NOT available outside of the IF Statement

Would be grateful for any help

Regards

Ghost

Steven
  • 166,672
  • 24
  • 332
  • 435
user343164
  • 11
  • 1
  • 2

2 Answers2

7
var OrdersByBranches = 
    from a in AllOrders 
    join b in AllBranchKeys on a.BranchKey equals b.BranchKey 
    orderby a.Date 
    group a by new { a.Date, a.paymentMethod } into BranchOrderGrouped 
    select new { 
        BranchOrderGrouped.Key.Date, 
        CurrencyAmount = BranchOrderGrouped.Sum(a =>  a.CurrencyAmount), 
        BranchOrderGrouped.Key.paymentMethod 
    };

if(string.IsNullOrEmpty(BranchKeySelected ))
{
    OrdersByBranches = OrdersByBranches.Where(/*blbabla*/);
}

return OrdersByBranches; 
Stephan
  • 4,187
  • 1
  • 21
  • 33
Gregoire
  • 24,219
  • 6
  • 46
  • 73
  • I think you have the conditional reversed from the question :) – jball May 17 '10 at 14:53
  • @jball: Maybe it's on purpose, to teach a lesson to people who copy and paste code before reading and understanding it? – Matti Virkkunen May 17 '10 at 14:56
  • I've a similar problem with dynamical grouping using LINQ. Can you please have a look [here](http://stackoverflow.com/questions/22694680/how-to-use-linq-for-conditional-grouping-and-filtering-on-a-datatable)? – Cheshire Cat Apr 01 '14 at 15:19
1

Try (and my linq is not polished)

var OrdersByBranches = from a in AllOrders 
    join b in AllBranchKeys on a.BranchKey equals b.BranchKey 
    where b.BranchKeySelected.Contains("")
    orderby a.Date group a by new 
        {
            a.Date, 
            a.paymentMethod
        }
        into BranchOrderGrouped
    select new
        {
            BranchOrderGrouped.Key.Date, 
            CurrencyAmount = BranchOrderGrouped.Sum(a =>  a.CurrencyAmount),
            BranchOrderGrouped.Key.paymentMethod 
         };
Pure.Krome
  • 84,693
  • 113
  • 396
  • 647
gnome
  • 1,113
  • 2
  • 11
  • 19
  • `where b.BranchKeySelected.Contains("")`? Isn't that a typo? It will return `true` on all strings (except `null`). – Steven May 17 '10 at 16:14