List A:
1, 2, 3, 4
List B:
2, 5
How to check if list A contains any value from list B?
e.g. someth
You can check if a list is inside of another list with this
var list1 = new List<int> { 1, 2, 3, 4, 6 };
var list2 = new List<int> { 2, 3 };
bool a = list1.Any(c => list2.Contains(c));
For faster and short solution you can use HashSet
instead of List
.
a.Overlaps(b);
Overlaps documentation
This method is an O(n) instead of O(n^2) with two lists.
If you didn't care about performance, you could try:
a.Any(item => b.Contains(item))
// or, as in the column using a method group
a.Any(b.Contains)
But I would try this first:
a.Intersect(b).Any()
I've profiled Justins two solutions. a.Any(a => b.Contains(a))
is fastest.
using System;
using System.Collections.Generic;
using System.Linq;
namespace AnswersOnSO
{
public class Class1
{
public static void Main(string []args)
{
// How to check if list A contains any value from list B?
// e.g. something like A.contains(a=>a.id = B.id)?
var a = new List<int> {1,2,3,4};
var b = new List<int> {2,5};
var times = 10000000;
DateTime dtAny = DateTime.Now;
for (var i = 0; i < times; i++)
{
var aContainsBElements = a.Any(b.Contains);
}
var timeAny = (DateTime.Now - dtAny).TotalSeconds;
DateTime dtIntersect = DateTime.Now;
for (var i = 0; i < times; i++)
{
var aContainsBElements = a.Intersect(b).Any();
}
var timeIntersect = (DateTime.Now - dtIntersect).TotalSeconds;
// timeAny: 1.1470656 secs
// timeIn.: 3.1431798 secs
}
}
}
You can Intersect the two lists:
if (A.Intersect(B).Any())
Sorry, if this is irelevant, but will return list with matches using FindAll() in case you need this:
private bool IsContain(string cont)
{
List<string> ListToMatch= new List<string>() {"string1","string2"};
if (ListToMatch.ToArray().Any(cont.Contains))
{
return false;
}
else
return true;
}
And usage:
List<string> ListToCheck = new List<string>() {"string1","string2","string3","string4"};
List<string> FinalList = ListToCheck.FindAll(IsContain);
The final list contains only the matched elements string1 and string2 from list to check. Can easy be switched to int List.