Select multiple records based on list of Id's with linq

前端 未结 4 888
再見小時候
再見小時候 2020-11-30 18:31

I have a list containing Id\'s of my UserProfile table. How can i select all UserProfiles based on the list of Id\'s i got in a var us

4条回答
  •  -上瘾入骨i
    2020-11-30 19:05

    Nice answers abowe, but don't forget one IMPORTANT thing - they provide different results!

      var idList = new int[1, 2, 2, 2, 2]; // same user is selected 4 times
      var userProfiles = _dataContext.UserProfile.Where(e => idList.Contains(e)).ToList();
    

    This will return 2 rows from DB (and this could be correct, if you just want a distinct sorted list of users)

    BUT in many cases, you could want an unsorted list of results. You always have to think about it like about a SQL query. Please see the example with eshop shopping cart to illustrate what's going on:

      var priceListIDs = new int[1, 2, 2, 2, 2]; // user has bought 4 times item ID 2
      var shoppingCart = _dataContext.ShoppingCart
                         .Join(priceListIDs, sc => sc.PriceListID, pli => pli, (sc, pli) => sc)
                         .ToList();
    

    This will return 5 results from DB. Using 'contains' would be wrong in this case.

提交回复
热议问题