What is the linq equivalent to the SQL IN operator

前端 未结 9 2012
梦如初夏
梦如初夏 2020-12-05 06:34

With linq I have to check if a value of a row is present in an array.
The equivalent of the sql query:

WHERE ID IN (2,3,4,5)

How can I

相关标签:
9条回答
  • 2020-12-05 07:00

    You can write help-method:

        public bool Contains(int x, params int[] set) {
            return set.Contains(x);
        }
    

    and use short code:

        var resultset = from x in collection
                        where Contains(x, 2, 3, 4, 5)
                        select x;
    
    0 讨论(0)
  • 2020-12-05 07:01

    .Contains

    var resultset = from x in collection where new[] {2,3,4,5}.Contains(x) select x
    

    Of course, with your simple problem, you could have something like:

    var resultset = from x in collection where x >= 2 && x <= 5 select x
    
    0 讨论(0)
  • 2020-12-05 07:03

    The above situations work when the Contains function is used against primitives, but what if you are dealing with objects (e.g. myListOrArrayOfObjs.Contains(efObj))?

    I found a solution! Convert your efObj into a string, thats separated by _ for each field (you can almost think of it as a CSV representation of your obj)

    An example of such may look like this:

         var reqAssetsDataStringRep = new List<string>();
    
            foreach (var ra in onDemandQueueJobRequest.RequestedAssets)
            {
                reqAssetsDataStringRep.Add(ra.RequestedAssetId + "_" + ra.ImageId);
            }
    
            var requestedAssets = await (from reqAsset in DbContext.RequestedAssets
                                         join image in DbContext.Images on reqAsset.ImageId equals image.Id
                                         where reqAssetsDataStringRep.Contains(reqAsset.Id + "_" + image.Id)
                                         select reqAsset
                                               ).ToListAsync();
    
    0 讨论(0)
提交回复
热议问题