Need help in LINQ: Contains clause

Jerry Lipan 916 Reputation points
2022-04-19T09:13:23.683+00:00

Hi. This is my table
194158-19042022-002.png

I've successfully getting all data using below

 var _SFAProject = _context2.SFAProject.ToList();  

Now I want to filter using Contains. Let say, I've have ClientsId variable parameter as following,

('8', '6', '1', '18')  

Below LINQ it is not working,

var result = from s in _SFAProject  
                         where s.ClientsId.ToString().Contains("('8', '6', '1', '18')")  
                         select s;  

194226-19042022-003.png

194227-19042022-004.png

How to fix that ? ClientsId variable parameter can be

  1. ('2', '8', '6', '1', '13', '18')
  2. ('2', '8')
  3. ('1', '13', '18')
  4. ('6', '1')

If I need to change variable parameter format, please let me know

Please help

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,200 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,292 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,016 Reputation points Microsoft Vendor
    2022-04-20T02:22:48.227+00:00

    Hi @Jerry Lipan ,

    194387-image.png

    First, when using the contains methods like the above, it will check whether the clientid contain the specified element. Based on the code, for example the CliensId is 8, then using the above code, it will check whether it contains the "('8', '6', '1', '18')", and the result is clear, it can't find any items. More detail information about contains method, see Enumerable.Contains Method and Queryable.Contains Method.

    How to fix that ? ClientsId variable parameter can be
    ('2', '8', '6', '1', '13', '18')
    ('2', '8')
    ('1', '13', '18')
    ('6', '1')
    If I need to change variable parameter format, please let me know

    Then, based on your description, I assume you will receive an input value which might contain the above string value. After that, you could use Regex Matches to fill all clientsid from the input string, and put them into an array or list, then you can use the contains method to filter data.

    You can refer the following sample code:

    //test data  
    var _SFAProject = new List<SFAProject>()  
    {  
        new SFAProject(){ Id=1, TenderName="A", ClientsId= 6},  
        new SFAProject(){ Id=2, TenderName="B", ClientsId= 18},  
        new SFAProject(){ Id=3, TenderName="C", ClientsId= 13},  
        new SFAProject(){ Id=4, TenderName="D", ClientsId= 13},  
        new SFAProject(){ Id=5, TenderName="E", ClientsId= 8},  
    };  
    //the input value  
    var inputclientsid = "('8', '6', '1', '18')";  
    //use regex to find all clientsid  
    string pattern = @"\b[0-9]+\b";  
    Regex rgx = new Regex(pattern);  
    //find all clients id and store them into a list.  
    var ids = rgx.Matches(inputclientsid).Cast<Match>().Select(c => c.Value).ToList();  
       
    //filter data based on the input clientsid  
    var filterresult = (from s in _SFAProject  
                        where ids.Contains(s.ClientsId.ToString())  
                        select s).ToList();  
    //you can also use this method  
    var filterresult2 = (from s in _SFAProject  
                        where ids.Any(c=> c == s.ClientsId.ToString())  
                        select s).ToList();  
    

    Then, the result like this:
    194417-1.gif


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. George Kalchev 1 Reputation point
    2022-04-19T09:24:05.277+00:00

    Hello,
    You are converting integer to string which means that it will be single number for example 6 or 18, and this for sure cannot contains the string which you are passing.
    If you want to check a single integer to be in an array of integers you have to create one with the accepted values:

    public IActionResult ViewSpreadsheet (string Id)
    var acceptedClients = new int[]{  8, 6, 1, 18};
    var SFAProject =context2. SFAProject.ToList();
    var result = from s in SFAProject
                       where acceptedClients.Contains(s.ClientsId)
                       select S;
    
    List‹object› data = new List<object»()...;
    
    0 comments No comments

  2. Karen Payne MVP 35,196 Reputation points
    2022-04-19T11:35:37.54+00:00

    From where s.ClientsId.ToString().Contains("('8', '6', '1', '18')") it appears ClientsId is perhaps an int and if this is the case you can use the code in the following repository.

    Usage, in this example use Entity Framework an array of object is created for primary keys for the model Customer.

    public async Task Demo()
    {
        var keys = new object[] { 1, 2, 3, 4 };
        await using var context = new NorthwindContext();
        Customers[] customers = await context.FindAllAsync<Customers>(keys);
    }
    

    Since FindAllAsync is generic it works for any model and since the parameter keyValues is an array that is variable in size you can pass in any amount of keys.

    One of the code samples shown below when Get selected is clicked gets the category identifiers and passes them to FindAllAsync and returns in this case Products with the selected categories.

    Added benefits is that Entity Framework will parameterize values sent to the database rather than raw keys.

    0 comments No comments