从不同类型的列表中搜索名称

searches a name from list of different types

我已经尝试了下面的一些逻辑,但我正在寻找更通用的解决方案,请帮我看看有没有其他方法可以获取对象。

static class FinObj
{
    public static ppl Find(List<ppl> obj, string Name)
    {
        foreach (var item in obj)
        {              
            if (item.Name == Name)
            { 
                return (item);
            }
        }
        return null;
    }
}
    
static void Main(string[] args)
{
      
    student d = FinObj.Find(stuList, "B") as student;

    teacher x = FinObj.Find(patientList, "BB") as teacher; 
}

您可以自己使用泛型。这样,您一旦声明的方法将自动 return 正确的 class:

using System;
using System.Collections.Generic;
using System.Linq; 

class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
    public char Gender { get; set; }

    public override string ToString() => $"{GetType()}  {ID}  {Name}  {Gender}"; 
}

class Patient : Person { } 
class Doctor : Person { }

static class FinderObject
{
    // what you want to do can be done using Linq on a list with FirstOrDefault
    // so there is no real use to create the method yourself if you could instead
    // leverage linq
    public static T Find<T>(List<T> data, string Name)
        where T : Person 
        => data.FirstOrDefault(p => p.Name == Name);
}

用法:

public static class Program
{
    static void Main(string[] args)
    {
        var docList = Enumerable.Range(1, 10)
            .Select(n => new Doctor() { ID = n, Name = $"Name{n}", Gender = 'D' })
            .ToList();

        var patientList = Enumerable.Range(100, 110)
            .Select(n => new Patient() { ID = n, Name = $"Name{n}", Gender = 'D' })
            .ToList(); 

        // finds a doctor by that name
        Doctor d = FinderObject.Find(docList, "Name3");

        // patient does not exist
        Patient x = FinderObject.Find(patientList, "Name99");

        Console.WriteLine($"Doc: {d}");
        Console.WriteLine($"Pat: {(x != null ? x.ToString() : "No such patient")}");
        Console.ReadLine();
    } 
}

输出:

Doc: Doctor  3  Name3 D
Pat: No such patient

参见:

 public static dynamic Find(List<Person> obj, string Name)
        {
            var result = obj.Find(x => x.Name == Name);

            if (result != null)
            {
                Console.WriteLine("ID:" + result.ID + ", Name:" + result.Name + ", Gender:" + result.Gender);
            }
            Console.WriteLine("Not Found");
            return result;

        }