-1

I have Table like ProductInventory , In that I have some product with quantity .

I want select all rows where The least of a field equals to my input(number) .

I try with this :

List<product> Products = new List<product> { 
    new product{Id=1,Name="A",Quantity=1},
    new product{Id=1,Name="A",Quantity=2},
    new product{Id=1,Name="A",Quantity=3},
    new product{Id=1,Name="B",Quantity=4},
    new product{Id=1,Name="B",Quantity=7}
};

var result = Products
    .AsEnumerable()
    .GroupBy(r => r.Name)
    .Where(g => (int)g.Sum(r =>r.Quantity)<= 4)
    .ToList();

but it causes a return zero.

example: enter image description here

Uthman Rahimi
  • 708
  • 5
  • 22

2 Answers2

2

I don't know is it possible in linq or not. But you can try this.

var result = Products.AsEnumerable().Where(g => g.Name == "A").ToList();

int userInput =4;
var total = 0;
var selectList = new List<product>();
for (int i = 0; i < result.Count; i++)
{
   for (int j = i; j < result.Count; j++)
    {
      if (total + result[j].Quantity <= userInput)
      {
         total += result[j].Quantity;
         selectList.Add(result[j]);
       }
     }
     if (total == userInput)
       break;
     else
     {
        total = 0;
        selectList = new List<product>();
      }
}
if(userInput!=total)
 selectList = new List<product>();
reza.cse08
  • 5,938
  • 48
  • 39
1

With that latest update, I think I finally understand what you are trying to do.

This won't work however, because you cant build the sum of booleans.

var result = Products
    .AsEnumerable()
    .GroupBy(r => r.Name)
    .Where(g => g.Sum(r =>r.Quantity== 4))
    .ToList();

What you actually want is

var result = Products
    .GroupBy(r => r.Name)
    .Where(g => g.Sum(r =>r.Quantity) >= 4) //or == 4 or whatever
    .ToList();
Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62