1

I have the following LINQ query where clause which isn't returning the expected result. dtTemp row.Item(0) has values like "GE", "LE", "ST", "PL" while Stkyard is a string array with one or more of these values.

I am expecting the below query to filter values based on entry in Stkyard but the returned result set has sum of all values in dtTemp

dtQuery = (From row In dtTemp
           Group row By grp = 
           New With {Key .mth = row.Item(1), Key .mthdesc = row.Item(2)} Into Group, 
           val1 = Sum(Convert.ToDecimal(row.Item(3))), val2 = Sum(Convert.ToDecimal(row.Item(4)))
           Where Group.Any(Function(p) Stkyard.Contains(p.Item(0)))
           Select New With {grp.mth, grp.mthdesc, val1, val2}
           Distinct).ToList

Any help?

DonNetFiddle Example

2
  • Can you share a .NETFiddle example? Commented May 12, 2016 at 8:59
  • @aloisdg I have added an example in the post. Commented May 12, 2016 at 9:30

1 Answer 1

3

You've grouped by Month before you filter, and then you filter for any groups where any matches are found. For example, your Jan 16 Group contains 3 rows, one from each Type, and your filter matches the whole group as it contains one of the items in Stkyard.

To fix this, filter the rows before you group:

dtQuery = (From row In dtTemp
       Where Stkyard.Contains(row.Item(0))
       Group row By grp = 
       New With {Key .mth = row.Item(1), Key .mthdesc = row.Item(2)} Into Group, 
       val1 = Sum(Convert.ToDecimal(row.Item(3))), val2 = Sum(Convert.ToDecimal(row.Item(4)))
       Select New With {grp.mth, grp.mthdesc, val1, val2}
       Distinct).ToList

Updated Fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

Thank! I was under the impression that Where clause always comes after Group By clause.
You can use as many wheres as you like. If you use it after the Group, you're filtering the groups (more like a HAVING in SQL).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.