Сравнить два списка для поиска общих элементов
List<int> one //1, 3, 4, 6, 7
List<int> second //1, 2, 4, 5
Как получить все элементы из одного списка, которые присутствуют и во втором списке?
В этом случае должно быть: 1, 4
Я говорю, конечно, о методе без foreach. Скорее linq-запрос
Ответы
Ответ 1
Вы можете использовать метод Intersect.
var result = one.Intersect(second);
Пример:
void Main()
{
List<int> one = new List<int>() {1, 3, 4, 6, 7};
List<int> second = new List<int>() {1, 2, 4, 5};
foreach(int r in one.Intersect(second))
Console.WriteLine(r);
}
Вывод:
1
4
Ответ 2
static void Main(string[] args)
{
List<int> one = new List<int>() { 1, 3, 4, 6, 7 };
List<int> second = new List<int>() { 1, 2, 4, 5 };
var result = one.Intersect(second);
if (result.Count() > 0)
result.ToList().ForEach(t => Console.WriteLine(t));
else
Console.WriteLine("No elements is common!");
Console.ReadLine();
}