Contains函数应用 IEqualityComparer 示例

Contains函数应用 IEqualityComparer 示例

项目中涉及到了比较器的应用,截图如下:
在这里插入图片描述
现将 Contains函数应用 IEqualityComparer 做一个完整的示例如下:

bool b = stuList.Contains(stu, new IDComparater());

一、引用函数

#region 程序集 System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2\System.Core.dll
#endregion

// 参数:
source:  要在其中定位某个值的序列。
value: 要在序列中定位的值。
comparer: 一个对值进行比较的相等比较器。
TSource: source元素的类型
返回结果: true 如果源序列包含具有指定的值; 的元素否则为 falsepublic static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer);

二、示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Student> stuList = new List<Student> {
                new Student(1002,"学生1",20),
                new Student(1003,"学生2",30),
                new Student(1001,"张三",20),
                new Student(1004,"学生3",30),
                new Student(1001,"张三",20),
                new Student(1005,"学生4",20),
                new Student(1006,"学生5",30),
                new Student(1007,"学生6",20),
                new Student(1008,"学生7",30),
                new Student(1009,"学生8",200),
            };

            //ID=1001的学生张三,后期进行了更名,如何判断这个改名后的学生是否包含在 学生名册中呢?
            var stu = new Student(1001, "张飞", 5);
            bool b = stuList.Contains(stu, new IDComparater());
            //b==true     
        }
    }

    class IDComparater : IEqualityComparer<Student>
    {
        public bool Equals(Student x, Student y)
        {
            return x.ID == y.ID;
        }

        public int GetHashCode(Student obj)
        {
            return 0;
        }
    }

    class Student
    {
        public Student(int iD, string name, int age)
        {
            ID = iD;
            Name = name;
            Age = age;
        }

        public int ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

    }
}

上述代码,只查找到第1个符合条件的即结束继承查找

发布了132 篇原创文章 · 获赞 16 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/cxb2011/article/details/104586828