【发布时间】:2012-07-31 12:24:16
【问题描述】:
List<int> one //1, 3, 4, 6, 7
List<int> second //1, 2, 4, 5
如何从一个列表中获取同时存在于第二个列表中的所有元素?
在这种情况下应该是:1, 4
我当然会谈论没有 foreach 的方法。而是 linq 查询
【问题讨论】:
标签: c# linq comparison
List<int> one //1, 3, 4, 6, 7
List<int> second //1, 2, 4, 5
如何从一个列表中获取同时存在于第二个列表中的所有元素?
在这种情况下应该是:1, 4
我当然会谈论没有 foreach 的方法。而是 linq 查询
【问题讨论】:
标签: c# linq comparison
您可以使用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
【讨论】:
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();
}
【讨论】: