ElementCollection and LINQ using C# and .NET

  1. Add SautinSoft.Document from Nuget.
  2. Load a DOCX document.
  3. Find all paragraphs marked as list.

Complete code

using System;
using System.Linq;
using SautinSoft.Document;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            ShowLists();
        }
        /// <summary>
        /// Find all paragraphs in a document marked as list (ordered or unordered).
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/elementcollection-linq.php
        /// </remarks>
        static void ShowLists()
        {
            string filePath = @"..\..\..\example.docx";
            DocumentCore dc = DocumentCore.Load(filePath);

            // Select all paragraphs marked as list using LINQ.
            var selectedPars = from p in dc.GetChildElements(true, ElementType.Paragraph)
                               where (p as Paragraph).ListFormat.IsList
                               select p;

            foreach (Paragraph p in selectedPars)
                Console.WriteLine(p.Content.ToString().TrimEnd());

            Console.ReadKey();
        }
    }
}

Download

Imports System
Imports System.Linq
Imports SautinSoft.Document
Module Sample
    Sub Main()
        ShowLists()
    End Sub
    ''' Get your free 30-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' Find all paragraphs in a document marked as list (ordered or unordered).
    ''' </summary>
    ''' <remarks>
    ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/elementcollection-linq.php
    ''' </remarks>
    Sub ShowLists()
        Dim filePath As String = "..\..\..\example.docx"
        Dim dc As DocumentCore = DocumentCore.Load(filePath)

        ' Select all paragraphs marked as list using LINQ.
        Dim selectedPars = From p In dc.GetChildElements(True, ElementType.Paragraph)
                           Where (TryCast(p, Paragraph)).ListFormat.IsList
                           Select p

        For Each p As Paragraph In selectedPars
            Console.WriteLine(p.Content.ToString().TrimEnd())
        Next p

        Console.ReadKey()
    End Sub
End Module

Download

If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page).