Search code examples
c#linqmorelinq

Linq Where Clause combined with Conditional


I'm in a bit of problem here. I have an Linq statment that filters an list of objects from an Database.

Suppose I have the following list of elements(each '{...}' represents one object from the list):

{id: 288, id_price_table: 1},
{id: 295, id_price_table: 1},
{id: 295, id_price_table: 2},
{id: 295, id_price_table: 3}

And I have two paramters, One is 'StandardPriceTable' and the other one is 'CurrentUserPriceTable'. In my case these paramters are the following:

Int32 StandardPriceTable = 1;
Int32 CurrentUserPriceTable = 2;

Now what I want to achieve is: Make an where clause that takes the conditional if the id is unique (and thus belongs to the StandardPriceTable) it returns the current object to the list.

But if the same ID belongs to lots of id_price_table than it should verify which one of the objects belongs to CurrentUserPriceTable returning only that object excluding others with the same ID.

I know I can achieve this with a foreach statement but that would cause an database query that I want to avoid by the time being.

Based on the conditions I've told the result of the query would equals to: IQueryable with the following itens:

{id: 288, id_price_table: 1},
{id: 295, id_price_table: 2}

Solution

  • How about:

    var result = from item in Items
                 group item by item.Id into g
                 select g.Single(i => g.Count() == 1 ? 
                                      true : 
                                      i.Id_price_table == CurrentUserPriceTable);
    

    or using lambdas:

    var result2 = Items.GroupBy(i => i.Id)
                       .Select(g => g.Single(i => g.Count() == 1 ? 
                                                  true : 
                                                  i.Id_price_table == CurrentUserPriceTable));