比较两个列表以搜索常见项目
List one //1, 3, 4, 6, 7 List second //1, 2, 4, 5
如何从第二个列表中的一个列表中获取所有元素?
在这种情况下应该是:1,4
我当然谈论没有foreach的方法。 而是linq查询
您可以使用Intersect方法。
var result = one.Intersect(second);
例:
void Main() { List one = new List () {1, 3, 4, 6, 7}; List second = new List () {1, 2, 4, 5}; foreach(int r in one.Intersect(second)) Console.WriteLine(r); }
输出:
1
4
static void Main(string[] args) { List one = new List () { 1, 3, 4, 6, 7 }; List second = new List () { 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(); }