tags:

views:

112

answers:

2

Hi All

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

+5  A: 
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; 
Gregoire
I think you have the conditional reversed from the question :)
jball
@jball: Maybe it's on purpose, to teach a lesson to people who copy and paste code before reading and understanding it?
Matti Virkkunen
No sorry, it was not intentional ;) I have corrected it
Gregoire
+1  A: 

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 
         };
gnome
`where b.BranchKeySelected.Contains("")`? Isn't that a typo? It will return `true` on all strings (except `null`).
Steven