确定列表中是否重复具有特定值的对象

时间:2017-12-13 07:20:29

标签: c#

我有一个具有名字和姓氏属性的Customer类。另外,我有一份客户名单。

public static List<Customer> customersList = new List<Customer>();

给出名字和姓氏,找出这个名字是否多次出现在名单上的最简洁方法是什么?

1 个答案:

答案 0 :(得分:1)

定义类

   public class Customer
    {
        public string FName { get; set; }
        public string LName { get; set; }
        public int Count { get; set; }
    }

在此查询

        List<Customer> list = new List<Customer>();
        list.Add(new Customer() { FName = "A", LName = "L" });
        list.Add(new Customer() { FName = "A", LName = "L" });
        list.Add(new Customer() { FName = "B", LName = "L" });
        list.Add(new Customer() { FName = "B", LName = "L" });
        list.Add(new Customer() { FName = "C", LName = "L" });

        var isDup = list.Where(x => x.FName.Equals("A") && x.LName.Equals("L")).Count() > 1;
        var isNotDup = list.Where(x => x.FName.Equals("C") && x.LName.Equals("L")).Count() > 1;

结果

isDup is true
isNotDup is false