locked
LINQ - How to check elements from List A to List B RRS feed

  • Question

  • User-1024101449 posted

    Hi,

    I have two list and i want to check and contains the elements from A to B.

    For example,

    List<string> List1 =  { "a1","a2"};
    List<string> List2 = {"m1","m2","a1","a","a1" };

    I want to check {a1,a2} in List B.

    I need exactly, it sholud check both a1 and a2. even it will not available any one like a1 or a2 then it should return false.

    If both will match (a1 and a2) then it should return true else return false.

    I write the below code. but, it will check any.

    But, i want it should match both cases a1 and a2.

    my linq :

     var Qry = List2.Where(t2 => List1.Any(t1 => t2.Contains(t1))).Count();

    the above query even if any one values contains it return count.

    But, i need both should check in list2.

    How to write in Linq simple query.

    Friday, June 23, 2017 9:55 AM

Answers

  • User-1509636757 posted

    I guess you only need to check the query result count against List1 count to verify if all items are there in the List2 or not. Here is an example based on your code scenario:

    public partial class WebForm235 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            List<string> List1 = new List<string>() { "a1", "a2" };
            List<string> List2 = new List<string>() { "m1", "m2", "a1", "a", "a1" };
            var Qry = List2.Where(t2 => List1.Any(t1 => t2.Contains(t1))).Distinct().Count();
            if (Qry == List1.Count)
            {
                //-- found all items, true
            }
            else
            {
                //-- either found no items, or some of items (not all)
            }
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, June 23, 2017 11:27 AM