此例实现通过自定义查询类来实现List的查询:
要查询的类定义如下:
public partial class XTeacher
{
private string m_Name = string.Empty;
public string Name
{
get { return this.m_Name; }
set { this.m_Name = value; }
}
private string m_Id = string.Empty;
public string Id
{
get { return this.m_Id; }
set { this.m_Id = value; }
}
public XTeacher(string name, string id)
{
this.m_Name = name;
this.m_Id = id;
}
}自定义查询类实现代码如下:
public partial class XTeacherFinder
{
private string m_TeacherId = string.Empty;
public string TeacherId
{
get { return m_TeacherId; }
set { this.m_TeacherId = value; }
}
private string m_TeacherName = string.Empty;
public string TeacherName
{
get { return this.m_TeacherName; }
set { this.m_TeacherName = value; }
}
public XTeacherFinder()
{
}
/// <summary>
/// 通过ID查找
/// </summary>
/// <param name="teacher"></param>
/// <returns></returns>
public bool FindTeacherById(XTeacher teacher)
{
return m_TeacherId == teacher.Id;
}
/// <summary>
/// 通过名称查找
/// </summary>
/// <param name="teacher"></param>
/// <returns></returns>
public bool FindTeacherByName(XTeacher teacher)
{
return m_TeacherName == teacher.Name;
}
/// <summary>
/// 通过ID和名称查找
/// </summary>
/// <param name="teacher"></param>
/// <returns></returns>
public bool FindTeacherByIdAndName(XTeacher teacher)
{
return (m_TeacherName == teacher.Name && m_TeacherId == teacher.Id);
}
}客户端调用方法如下:
static void Main(string[] args)
{
List<XTeacher> teachers = new List<XTeacher>();
XTeacher teacher = new XTeacher("test1", "1");
teachers.Add(teacher);
teacher = new XTeacher("test2", "2");
teachers.Add(teacher);
teacher = new XTeacher("test2", "3");
teachers.Add(teacher);
XTeacherFinder teacherFinder = new XTeacherFinder();
teacherFinder.TeacherId = "1";
XTeacher findedTeacher = teachers.Find(teacherFinder.FindTeacherById);
Console.WriteLine("通过ID找到教师:{0},{1}", findedTeacher.Id, findedTeacher.Name);
XTeacherFinder finder=new XTeacherFinder();
finder.TeacherName="test2";
XTeacher findedTeacherByName = teachers.Find(finder.FindTeacherByName);
Console.WriteLine("通过名称找到教师:{0},{1}", findedTeacherByName.Id, findedTeacherByName.Name);
List<XTeacher> findedTeachers = teachers.FindAll(finder.FindTeacherByName);
foreach (XTeacher t in findedTeachers)
{
Console.WriteLine("通过名称找到教师集合:{0},{1}", t.Id, t.Name);
}
XTeacherFinder f = new XTeacherFinder();
f.TeacherId = "3";
f.TeacherName = "test2";
XTeacher fTeacher = teachers.Find(f.FindTeacherByIdAndName);
Console.WriteLine("通过ID和名称找到教师:{0},{1}", fTeacher.Id, fTeacher.Name);
Console.Read();
}
C#实现List集合的自定义查询简介
最新推荐文章于 2024-09-10 13:06:19 发布