Search code examples
c#listcontains

how to use contains on list of string with where clause


When I am trying to filter records that match any item in the search list then it's not returning me anything. please see code

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Test {

    // Main Method
    public static void Main(String[] args)
    {
        List<String> searchlist = new List<String>();
        searchlist.Add("Mang");
        searchlist.Add("Apple");
        
        List<String> firstlist = new List<String>();
        firstlist.Add("Mango");
        firstlist.Add("Apple");
        firstlist.Add("Orange");
        firstlist.Add("Grapes");
        
        test1 obj = new test1();
        obj.stringList = firstlist;

        Console.Write(obj.stringList.Where(x=> searchlist.Contains(x)).Count());
    }
    
    public class test1
    {
        public string id { get; set; }
        public string name { get; set; }
        public List<String> stringList { get; set; }
    }
}

In the above example, if I will pass a full string like "Mango" then it will return the result but if I try to search only "Mang" (partial words) then it's not working.


Solution

  • Try this

    Console.Write(obj.stringList.Where(x => searchlist.Any(list => x.Contains(list))).Count());