1

我正在为此寻找一种 LINQ 删除方法:

<ArrayOfGroup>
    <Group>
        <GroupName>c</GroupName>
        <StudentList>
             <Student>
                 <TimeAdded>0001-01-01T00:00:00</TimeAdded> // trying to delete from here
                 <StudentID>1</StudentID>
                 <FirstName>a</FirstName>
                 <LastName>b</LastName> // to here
                 <StudentGroup/>
             </Student>
        </StudentList>
    </Group>
</ArrayOfGroup>

出于某种原因,当我以这种方式删除它时:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] 
public class Service : IService
{
    List<Student> students = new List<Student>();
    List<Group> Groups = new List<Group>();
    public void removeStudent(string studentID)
    {
        students.Remove(students.Find(f => f.StudentID.Equals(studentID)));
        //var result = students.Where(n => String.Equals(n.StudentID, studentID)).FirstOrDefault();
        //if (result == null)
        //{
        //    result.StudentGroup.Remove(StudentList.Student.Find(f => f.StudentID.Equals(studentID)));
        //}
        // students.RemoveAll(f => f.StudentID.Equals(studentID)); also tryed this
    }

它不会从我的 ArrayOfGroup 的学生列表/学生区域中删除它,所以我厌倦了试图解决它不删除的原因,只是试图找到一种新方法将它与原始记录一起删除。我觉得这样做是个罪犯,但如果有人能提供帮助,我将不胜感激。

我的数据合同如下所示:

[DataContract(Name="Student")]
public class Student
{
    public Student()
    {
        StudentGroup = new List<Group>();
    }

    [DataMember(Name = "StudentID")]
    public string StudentID { get; set; }

    [DataMember(Name = "FirstName")]
    public string FirstName { get; set; }

    [DataMember(Name = "LastName")]
    public string LastName { get; set; }

    [DataMember(Name = "TimeAdded")]
    public DateTime TimeAdded;

    public string TimeAddedString
    {
        get
        {
            return this.TimeAdded.ToString("dd/MM/yyyy hh:mm:ss");
        }
    }

    public List<Group> StudentGroup { get; set; }
}

[DataContract(Name = "Group")]
public class Group
{
    public Group() 
    {
        StudentList = new List<Student>();
    }

    [DataMember(Name = "GroupName")]
    public string GroupName { get; set; }

    public List<Student> StudentList { get; set; }
}

如果有帮助,这就是将学生添加到组中的方式吗?

public void AddStudentToGroup(string group, string studentID, string firstName, string lastName)
{
    var result = Groups.Where(n => String.Equals(n.GroupName, group)).FirstOrDefault();
    var result1 = students.Where(n => String.Equals(n.StudentID, studentID)).FirstOrDefault();
    if (result != null)
    {
        result.StudentList.Add(new Student() { StudentID = studentID, FirstName = firstName, LastName = lastName });
    }
    if (result1 != null)
    {
        result1.StudentGroup.Add(new Group() { GroupName = group });
    }
}  
4

1 回答 1

1

您可以Remove在对象上使用该方法,该方法List<T>采用如下谓词:

students.RemoveAll(s => s.StudentId == 5);
于 2012-04-12T15:33:39.523 回答