gpt4 book ai didi

c# - 使用 LINQ 比较列表并返回常见对象

转载 作者:太空狗 更新时间:2023-10-29 22:04:16 25 4
gpt4 key购买 nike

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; }
}

}

我如何比较这两个列表并仅找到出现在 custList 和 vendorList 中的那些客户?

最佳答案

理想情况下,使您的 Customer类覆盖 GetHashCodeEquals (更好的是,实现 IEquatable<Customer> )。然后你可以使用:

var customerVendors = custList.Intersect(vendorList);

否则,您将实现 IEqualityComparer<T>比较客户是否平等(例如按名称,但您可以选择其他比较)然后使用:

var customerVendors = custList.Intersect(vendorList, new CustomerComparer());

请注意,它们都将返回 IEnumerable<Customer> ,这将被延迟评估。有时这就是你想要的,但如果你真的需要 List<Customer> , 只需调用 ToList()在最后,例如

var customerVendors = custList.Intersect(vendorList).ToList();

关于c# - 使用 LINQ 比较列表并返回常见对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5707165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com