using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
List<Customer> custList = new List<Customer>();
custList.Add(new Customer { Name = "P1" });
custList.Add(new Customer { Name = "P2" });
custList.Add(new Customer { Name = "P3" });
custList.Add(new Customer { Name = "P4" });
custList.Add(new Customer { Name = "P5" });
List<Customer> vendorList = new List<Customer>();
vendorList.Add(new Customer { Name = "P1" });
vendorList.Add(new Customer { Name = "P2" });
//var v = custList.SelectMany(
}
}
public class Customer
{
public string Name { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
如何复制这两个列表并仅查找custList和vendorList中存在的那些客户?
Jon*_*eet 13
理想的情况下,让你的Customer
类重写GetHashCode
和Equals
(更重要的是,实施IEquatable<Customer>
).然后你可以使用:
var customerVendors = custList.Intersect(vendorList);
Run Code Online (Sandbox Code Playgroud)
否则,您将实现IEqualityComparer<T>
比较客户的相等性(例如,通过名称,但您可以选择其他比较),然后使用:
var customerVendors = custList.Intersect(vendorList, new CustomerComparer());
Run Code Online (Sandbox Code Playgroud)
请注意,这些都会返回IEnumerable<Customer>
,这将被懒惰地评估.有时这就是你想要的,但如果你真的需要一个List<Customer>
,最后只需要打电话ToList()
,例如
var customerVendors = custList.Intersect(vendorList).ToList();
Run Code Online (Sandbox Code Playgroud)
从评论到另一个答案:
Intersect期望两个列表具有相同的类型.如果它们的类型不同,如果两个列表中的属性名称不同,该怎么办?我如何在这里使用SelectMany
在这种情况下,您可能希望使用Join
.如
var result = from item1 in list1
join item2 in list2
on item1.Foo equals item2.Bar
select new { item1, item2 }; // select whatever you need in the resultset
Run Code Online (Sandbox Code Playgroud)