如何使用 LINQ 为链接到多个辅助对象的任何对象返回包含多个记录的列表?

问题描述 投票:0回答:1

我有一个

Form
对象列表,每个
Form
对象都通过链接表链接到
Subject
对象。如果其中一个表单链接到多个主题,我如何使用 LINQ 返回表单列表,其中具有多个主题的每个表单在列表中出现两次并带有相关主题 ID?此外,我如何才能将该列表中具有相同
TypeId
SubjectId
的表单分组在一起?

这是我的代码来重现我正在谈论的情况:

public class Form
{
    public int Id { get; set; }
    public int TypeId { get; set; }
    public string Name { get; set; }
    public List<FormSubjectLink> FormSubjectLinks { get; set; }
    public int SubjectId { get; set; } // to return the subject id to once isolated
}

public class Subject
{
    public int Id { get; set; }
}

public class FormSubjectLink
{
    public int FormId { get; set; }
    public int SubjectId { get; set; }
}

public List<Form> forms = new List<Form>() {
new Form { Id = 1, TypeId = 1, Name = "FormA1", FormSubjectLinks = new List<FormSubjectLink>() { new FormSubjectLink { FormId = 1, SubjectId = 1 } } },
new Form { Id = 2, TypeId = 1, Name = "FormA2", FormSubjectLinks = new List<FormSubjectLink>() { new FormSubjectLink { FormId = 2, SubjectId = 1 } } },
new Form { Id = 3, TypeId = 1, Name = "FormA3", FormSubjectLinks = new List<FormSubjectLink>() { new FormSubjectLink { FormId = 3, SubjectId = 2 } } },
new Form { Id = 4, TypeId = 2, Name = "FormB1", FormSubjectLinks = new List<FormSubjectLink>() { new FormSubjectLink { FormId = 4, SubjectId = 1 }, new FormSubjectLink { FormId = 4, SubjectId = 2 }}}};

我在这里想做的是拿走我的清单并返回

IEnumerable<IGrouping<(TypeId,SubjectId),Form>>
并附上以下物品:

类型 ID 主题ID 表格计数
1 1 2
1 2 1
2 1 1
2 2 1
c# linq
1个回答
0
投票

如果使用 LINQ 查询语法,则非常简单:

var result = from form in forms
    from link in form.FormSubjectLinks 
    // for each link in each form
    group form by (form.TypeId, link.SubjectId) into groups
    // group the forms by the type id and subject id
    select groups;

foreach (var x in result) {
    Console.WriteLine(x.Key);
    foreach(var y in x) {
        Console.WriteLine(y);
    }
}

示例输出(使用

ToString
record
格式):

(1, 1)
Form { Id = 1, TypeId = 1, Name = FormA1, FormSubjectLinks = System.Collections.Generic.List`1[FormSubjectLink], SubjectId = 0 }
Form { Id = 2, TypeId = 1, Name = FormA2, FormSubjectLinks = System.Collections.Generic.List`1[FormSubjectLink], SubjectId = 0 }
(1, 2)
Form { Id = 3, TypeId = 1, Name = FormA3, FormSubjectLinks = System.Collections.Generic.List`1[FormSubjectLink], SubjectId = 0 }
(2, 1)
Form { Id = 4, TypeId = 2, Name = FormB1, FormSubjectLinks = System.Collections.Generic.List`1[FormSubjectLink], SubjectId = 0 }
(2, 2)
Form { Id = 4, TypeId = 2, Name = FormB1, FormSubjectLinks = System.Collections.Generic.List`1[FormSubjectLink], SubjectId = 0 }

© www.soinside.com 2019 - 2024. All rights reserved.