Hmobius Notes |||

Handy LINQ stuff

Being a collection of useful LINQ-related notes and code that I don’t want to forget

  1. The ElementAt(n) method retrieves the n+1th item in a collection. It’s a lot more convenient that Skip(1).First() or Skip(1).Take(1).First()
  2. Use Enumerable.Empty<T> to initialize an IEnumerable<T> in the same way you would use new List<T>() to initialize a List<T>.
  3. The System.Linq.Enumerable class provides all the common LINQ related methods for an IEnumerable<T>.

  4. LINQ to aggregate strings

List<string> strings = new List<string>(){"one", "two", "three"};

StringBuilder sb = strings
  .Select(s => s)
  .Aggregate(
     new StringBuilder(), (ag, n) => ag.Append(n).Append(", "));
  1. LINQ to Unique XML Structures
IEnumerable<XElement> DistinctStructures(
   XContainer root, XName name)
{
   return
       from d in root.Descendants(name)
       group d by GetKey(d) into g
       select g.First();

   string GetKey(XElement n) =>
       String.Join(",",
           n.DescendantNodes().Select(d =>
               d is XElement e ? $"{e.Name}^{GetDepth(e)}"
               : d is XText t ? $"<text>^{GetDepth(t)}"
               : default
           )
       );
       
   int GetDepth(XObject o)
   {
       var depth = 0;
       for (var c = o; c != null; c = c.Parent)
           ++depth;
       return depth;
   }
}
Up next Visual Studio Code Setup Being a quick rundown of how I currently have VS Code setup. Candara is my coding font of choice. Monospace  glyphed fonts are not necessary.
Latest posts Handy LINQ stuff Visual Studio Code Setup C# Coding Standards, Mid 2019 Edition Inheritance Tracks Simic Flash in M20