嵌套类查询和连接

时间:2016-09-22 22:24:23

标签: linq

我有以下情况,在这种情况下,我看起来展平嵌套对象并将父字段和子字段组合在一行中,而不是创建父对象和子对象。

另外我想要结合v1和v2。任何建议?

public class Person
{
    public string idPerson;
    public string names;
    private List<Subject> subjects = new List<Subject>();
    private List<MedicalRecord> medicalRecords = new List<MedicalRecord>();
}

public class Subject
{
    public string subjectName;
    public string subjectId;
}

public class MedicalRecord
{
    public int recordId;
    public string doctorName;
    public string medicalCare;
}

void main()
{
    /// Assume that Person is filled.
    /// How can I join the two lists?

    List<Person> all = new List<Person>();
    var v1 = all.SelectMany(p => p.subjects, (child, parent) => new { child, parent });
    var v2 = all.SelectMany(p => p.medicalRecords, (child, parent) => new { child, parent }); /// here i want to select all fields instead of objects to avoid child and parent calling from below cycle.

    /// I want to join v1 and v2 and flatten the lists.
    foreach(var obj in v1)
    {
        Console.WriteLine(obj.child.subjectName + " "  + obj.parent.idPerson);
    }

    ///

}

1 个答案:

答案 0 :(得分:0)

您需要执行以下操作:

static void Main(string[] args)
{
    List<Person> all = new List<Person>();

    // Estract the flattened list of subjects
    var subjects = all.SelectMany(p => p.Subjects, (person, subject) => new { person.idPerson, person.names, subject});
    // Estract the flattened list of medical records
    var medicalRecords = all.SelectMany(p => p.MedicalRecords, (person, medicalRecord) => new { person.idPerson, person.names, medicalRecord});

    // Join the two lists and create a flattened object
    var flattenedList = 
        subjects.Join(medicalRecords,
                      s => s.idPerson,
                      m => m.idPerson,
                      (s, m) => new {
                          IdPerson = s.idPerson,
                          Names = s.names,
                          s.subject.SubjectId,
                          s.subject.SubjectName,
                          m.medicalRecord.RecordId,
                          m.medicalRecord.DoctorName,
                          m.medicalRecord.MedicalCare
                      })
                      .ToList();
}