About Links Archives Search Feed Albums of Note

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)
     new StringBuilder(), (ag, n) => ag.Append(n).Append(", "));
  1. LINQ to Unique XML Structures
IEnumerable<XElement> DistinctStructures(
   XContainer root, XName name)
       from d in root.Descendants(name)
       group d by GetKey(d) into g
       select g.First();

   string GetKey(XElement n) =>
           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)
       return depth;
Posted on August 25, 2019   #Code  

← Next post    ·    Previous post →