LINQ Grouping help

I have a database table that stores parent and child entries similar to a category table. The ParentID field of this table contains the identifier of the parent record entry ...

My table columns: SectionID, Title, Number, ParentID, Active

I just plan to allow parental relationships with the child go on two levels. Therefore, I have a section and a subsection and what it is.

I need to output this data to my MVC view page in the form of a diagram, for example ...

  • Section 1
    • Subsection 1 of 1
    • Subsection 2 of 1
    • Subsection 3 of 1
  • Section 2
    • Subsection 1 of 2
    • Subsection 2 of 2
    • Subsection 3 of 2
  • Section 3

Entity Framework 4.0 MVC 2.0 - LINQ. FK, , ParentID SEIDID, , EF "Section", Sub-Sections - , , , .

, , LINQ. - , , , ?

alt text

Update:

EDMX, , , .

var sections = from section in dataContext.Sections
                       where section.Active == true && section.ParentID == 0
                       orderby section.Number
                       select new Section
                       { 
                        SectionID = section.SectionID,
                        Title = section.Title,
                        Number = section.Number,
                        ParentID = section.ParentID,
                        Timestamp = section.Timestamp,
                        Active = section.Active,
                        Children = section.Children.OrderBy(c => c.Number)
                       };

. 'System.Linq.IOrderedEnumerable' 'System.Data.Objects.DataClasses.EntityCollection'

+3
2

Sections1 Section1. Children, - Parent.

, , , , ( NULL?), : -

  // assume top sections are ones where parent == self
  var topSections = context.Sections.Where(section => section.ParentId == SectionId);

  // now put them in order (might have multiple orderings depending on input, pick one)
  topSections = topSections.OrderBy(section => section.Title);

  // now get the children in order using an anonymous type for the projection
  var result = topSections.Select(section => new {top = section, children = section.Children.OrderBy(child => child.Title)});
+1

linq:

http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

linq, GroupBy. , , , , , , , . Linq - .

+1

Source: https://habr.com/ru/post/1768168/


All Articles