如何使用LINQ语句从集合中删除

本文关键字:集合 删除 语句 何使用 LINQ | 更新日期: 2024-10-24 13:26:48

我有一个用户定义的通用列表

public class DoctorsData
{
    string _doctorName;
    public string DoctorName { get { return _doctorName; } }
    string _doctorAge;
    public string DoctorAge { get { return _doctorAge; } }
    string _doctorCity;
    public string DoctorCity
    {
        get { return _doctorCity; }
        set { _doctorCity = value; }
    }
    string _doctorDesc;
    public string desc
    {
        get
        {
            return _doctorDesc;
        }
        set
        {
            _doctorDesc = value;
        }
    }
    public DoctorsData(string doctorname, string doctorage, string doctorcity, string doctordesc)
    {
        _doctorName = doctorname;
        _doctorAge = doctorage;
        _doctorCity = doctorcity;
        _doctorDesc = doctordesc;
    }
}

下面的代码用于将数据添加到列表中:-

List<DoctorsData> doctorlist = new List<DoctorsData>();
doctorlist.Add(new DoctorsData("mukesh", "32","sirsa","aclass"));
doctorlist.Add(new DoctorsData("rajesh", "29","hisar","bclass"));
doctorlist.Add(new DoctorsData("suresh", "25","bangalore","cclass"));
doctorlist.Add(new DoctorsData("vijay", "24","bangalore","cclass"));
doctorlist.Add(new DoctorsData("kumar anna", "40","trichi","aclass"));

我的要求是我想删除所有年龄小于30岁的医生条目。我们如何使用LINQ执行此操作。

如何使用LINQ语句从集合中删除

试试这个:

doctorList.RemoveAll(doctor => int.Parse(doctor.DoctorAge) < 30);

您可以添加一些额外的检查,以确保DoctorAge可以被解析为整数

int age = 0
doctorList.RemoveAll(D => int.TryParse(D.DoctorAge,out age) && age < 30);

希望这会有所帮助。