C# 使用LINQ比较列表并返回公共对象 使用系统; 使用System.Collections.Generic; 使用System.Linq; 使用系统文本; 命名空间控制台应用程序5 { 班级计划 { 静态void Main(字符串[]参数) { List custList=新列表(); 添加(新客户{Name=“P1”}); 添加(新客户{Name=“P2”}); 添加(新客户{Name=“P3”}); 添加(新客户{Name=“P4”}); 添加(新客户{Name=“P5”}); 列表供应商列表=新列表(); 添加(新客户{Name=“P1”}); 添加(新客户{Name=“P2”}); //var v=custList.SelectMany( } } 公共类客户 { 公共字符串名称{get;set;} } }
如何将这两个列表合并,并仅查找custList和vendorList中的客户?如果您的Customer类实现了“值”,如“C# 使用LINQ比较列表并返回公共对象 使用系统; 使用System.Collections.Generic; 使用System.Linq; 使用系统文本; 命名空间控制台应用程序5 { 班级计划 { 静态void Main(字符串[]参数) { List custList=新列表(); 添加(新客户{Name=“P1”}); 添加(新客户{Name=“P2”}); 添加(新客户{Name=“P3”}); 添加(新客户{Name=“P4”}); 添加(新客户{Name=“P5”}); 列表供应商列表=新列表(); 添加(新客户{Name=“P1”}); 添加(新客户{Name=“P2”}); //var v=custList.SelectMany( } } 公共类客户 { 公共字符串名称{get;set;} } },c#,linq,C#,Linq,如何将这两个列表合并,并仅查找custList和vendorList中的客户?如果您的Customer类实现了“值”,如“Equals()”,您可以执行以下操作: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication5 { class Program { static void Main(
Equals()”
,您可以执行以下操作:
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; }
}
}
否则,您可以使用传递自定义IEQualityComparer
的重载,该自定义IEQualityComparer
可以在单独的类中实现(即CustomerComparer
):
使用该方法。理想情况下,让您的
客户
类覆盖GetHashCode
和等于
(更好的是,实现IEquatable
)。然后您可以使用:
var inbothLists = custList.Intersect(vendorList, new CustomerComparer())
.ToList();
否则,您将需要实现一个IEqualityComparer
来比较客户是否平等(例如,通过名称,但您可以选择其他比较),然后使用:
var customerVendors = custList.Intersect(vendorList);
请注意,这两个函数都将返回IEnumerable
,这将被延迟计算。有时这正是您想要的,但是如果您确实需要列表
,只需在末尾调用ToList()
,例如
var customerVendors = custList.Intersect(vendorList, new CustomerComparer());
您只需要iQualityComparer根据名称进行比较。从一条评论到另一个答案:
Intersect希望两个列表都是相同的 同一类型。如果它们不是 相同类型,如果属性名为 两个列表中的内容不同?如何使用 在这里选择许多 在这种情况下,您可能希望利用
Join
var commonList = custList.Intersect(vendorList);
Intersect希望两个列表的类型相同。如果它们不是相同的类型,如果两个列表中的属性名称不同,该怎么办?我如何在这里使用SelectMany?@Asdfg:那么,老实说,你说的是另一个问题……你会使用联接。除了手动联接它们之外,还有其他方法吗?假设我有一个要查找的列表列表中的公共属性值?
var customerVendors = custList.Intersect(vendorList).ToList();
var commonList = custList.Intersect(vendorList);
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
var both = (from a in custList
join b in vendorList on a.Name equals b.Name
select a);