Ich versuche, verschachtelte Objekte wie folgt zu reduzieren:
public class Book
{
public string Name { get; set; }
public IList<Chapter> Chapters { get; set; }
}
public class Chapter
{
public string Name { get; set; }
public IList<Page> Pages { get; set; }
}
public class Page
{
public string Name { get; set; }
}
Lassen Sie mich ein Beispiel geben. Das sind die Daten, die ich habe
Book: Pro Linq
{
Chapter 1: Hello Linq
{
Page 1,
Page 2,
Page 3
},
Chapter 2: C# Language enhancements
{
Page 4
},
}
Das Ergebnis, das ich suche, ist die folgende flache Liste:
"Pro Linq", "Hello Linq", "Page 1"
"Pro Linq", "Hello Linq", "Page 2"
"Pro Linq", "Hello Linq", "Page 3"
"Pro Linq", "C# Language enhancements", "Page 4"
Wie könnte ich das erreichen? Ich könnte es mit einem select new machen, aber mir wurde gesagt, dass ein SelectMany ausreichen würde.
myBooks.SelectMany(b => b.Chapters
.SelectMany(c => c.Pages
.Select(p => b.Name + ", " + c.Name + ", " + p.Name)));
Angenommen, books
ist eine Liste von Büchern:
var r = from b in books
from c in b.Chapters
from p in c.Pages
select new {BookName = b.Name, ChapterName = c.Name, PageName = p.Name};
myBooks.SelectMany(b => b.Chapters
.SelectMany(c => c.Pages
.Select(p => new
{
BookName = b.Name ,
ChapterName = c.Name ,
PageName = p.Name
});
Ich habe auch versucht, dies zu tun, und aufgrund von Jurys Kommentaren und der Unordnung mit linqPad habe ich das ..
Beachten Sie, dass ich keine Bücher, Kapitel, Seiten, Personen (Bücher), FirmenPersonen (Kapitel) und Firmen (Seiten) habe.
from person in Person
join companyPerson in CompanyPerson on person.Id equals companyPerson.PersonId into companyPersonGroups
from companyPerson in companyPersonGroups.DefaultIfEmpty()
select new
{
ContactPerson = person,
ContactCompany = companyPerson.Company
};
oder
Person
.GroupJoin (
CompanyPerson,
person => person.Id,
companyPerson => companyPerson.PersonId,
(person, companyPersonGroups) =>
new
{
person = person,
companyPersonGroups = companyPersonGroups
}
)
.SelectMany (
temp0 => temp0.companyPersonGroups.DefaultIfEmpty (),
(temp0, companyPerson) =>
new
{
ContactPerson = temp0.person,
ContactCompany = companyPerson.Company
}
)
Referenz-Site, die ich verwendet habe: http://odetocode.com/blogs/scott/archive/2008/03/25/inner-outer-lets-all-join-together-with-linq.aspx