Understand linq expression RRS feed

  • Question

  • User-930352495 posted

    I have an entity named ItemBoxSup ( in table on db) and i have a method in which i pass list of items from extern of some type: ItemBoxLists.

    What i want to insert a check in or to see if there is atleast an existing item in my db in ItemBoxSup  with a flag set to true ,

    but i dont sure if i have to write :

    _context.ItemBoxSup.Any(y => y.IsActive == true) // using context

    or i can use directly 

    .Any(y => y.IsActive == true)  // or more concise

    because i dont understand if y is referred to item on table on db and if x is referred to items in the lists that i pass to method.

    public void ItemChecks(IEnumerable<ItemBoxSup> ItemBoxLists)

    var results=context.ItemBoxSup.Include(x => x.ItemBox) .Where(y => !y.IsDeleted && ItemBoxLists.Any(x => x.Id != y.Id && x.ItemBoxId == y.ItemBoxId || _context.ItemBoxSup.Any(y => y.IsActive == true)).ToList();
    // i can write? || Any(y => y.IsActive == true)).ToList()

    thanks to those who will help me understand.

    Wednesday, September 9, 2020 5:02 PM

All replies

  • User-1330468790 posted

    Hi first100,


    Could you please share the model for "ItemBoxSup" and "ItemBox"? 

    I also need the relationship between those two models so that I could tell you how you could construct the linq statement.

    Thank you for understanding.


    Apart from that, I think some tips might be useful to help you better understanding.

    • You could include the external ItemBoxLists into the condition with Any() method (which will return a bool value)
    • x or y is the exactly same here which both represent ItemBoxSup so that you could access any member/property of ItemBoxSup using x or y
    • You might be interested in Exists method which is used to determines whether the List<T> contains elements that match the conditions defined by the specified predicate. 
    •  Directly traverse the given list to see if it exists in the database
      public async Task<bool> IsIdListValid(IEnumerable<int> idList) =>
          idList.Any(id => !_context.Foo.Any(f => f.id == id));


    Hope this can help you.

    Best regards,


    Thursday, September 10, 2020 7:20 AM