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

时间:2013-12-18 09:50:56

标签: c# .net linq c#-4.0 linq-to-entities

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

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执行此操作。

2 个答案:

答案 0 :(得分:2)

试试这个:

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

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

答案 1 :(得分:1)

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

希望这会有所帮助。