Home > Software design >  Compare two list - check if one list contains value of second
Compare two list - check if one list contains value of second

Time:07-13

I'm trying to compare one list of string (list1) with next list (list2) values (next list of string). I found plenty of solution with sequence ordering but in my case it does not matter.

My list of string will be for example:

List<string> myList1 = new List() {'123', '234','345'}

Right now I need to create a method which will take list "1" as a parameter and then loops (?) through the list "2" to check if values from list 1 are in the list 2

public bool IsValueInsideTheList(string[] orderNumbersToFindInTheList)
{
 //Here I suppose I need to do the looping with foreach/ for to check if value of list1 are in the list2
}

CodePudding user response:

IEnumerable<string> list1;
IEnumerable<string> list2;

// ...
var containsMatches = list1.Any(item => list2.Contains(item));

I used IEnumerable<string> here because this will work for any lists of that type, not just a List<string> and a string[].

CodePudding user response:

You can use LINQ to achive this:

var commonList = list1.Intersect(list2)

CodePudding user response:

EDIT

I am not sure if this is what you wanted, but i will post anyways. This algorithm lets you compare the values from List 1 with the values AHEAD from List 2.

Example: List 1 Index 2 compared from List 2 Index 2 to the last value.

Even if this is not what you needed, i hope it helps someone.

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

namespace ListCompareItems
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> myList1 = new List<string>{ "123", "234", "345" };
            List<string> myList2 = new List<string> { "987", "123", "345", "112" };
            var comparisonLogic = (from item1 in myList1
                                  where (myList2.GetRange(
                                            myList1.IndexOf(item1),
                                            myList2.Count() - 1 - myList1.IndexOf(item1)).ToList().Contains(item1)
                                  )
                                  select item1).ToList();

            foreach (var output in comparisonLogic)
                Console.WriteLine(output);
        }
    }
}

Output:

123

345

Extras

You can edit this algorithm to return another answers.

If you want to know if there is at least one match, Count() the comparisonLogic. If it is greater than 0, there is a match.

You can return the Count() itself to know how many times there was a match.

CodePudding user response:

You can also use Intersect...Any(might be more efficient than Any...Contains):

bool intersectsWith = list1.Intersect(list2).Any();
  • Related