List<int> one //1, 3, 4, 6, 7
List<int> second //1, 2, 4, 5
How to get all elements from one list that are present also in second list?
如何从第二个列表中的一个列表中获取所有元素?
In this case should be: 1, 4
在这种情况下应该是:1,4
I talk of course about method without foreach. Rather linq query
我当然谈论没有foreach的方法。而是linq查询
2 个解决方案
#1
47
You can use the Intersect method.
您可以使用Intersect方法。
var result = one.Intersect(second);
Example:
例:
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);
}
Output:
输出:
1
41 4
#2
4
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();
}
#1
47
You can use the Intersect method.
您可以使用Intersect方法。
var result = one.Intersect(second);
Example:
例:
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);
}
Output:
输出:
1
41 4
#2
4
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();
}