title: Reduce Looping in Set Operations?
body: <p>Can I reduce the looping in this C# code, perhaps using better LINQ or lambda expressions? I'm essentially looking for a UNION operation that removes duplicates and flags the items that were in both sets.</p>
  
  <pre><code>public class LibraryLocation
  {
      public string HoldingType { get; set; }
      public string LibraryLocationName { get; set; }
  }
  
  public class HoldingRepo
  {
      public HoldingRepo(MyDbContext dbContext)
      {
      }
  
      public async Task&lt;List&lt;LibraryLocation&gt;&gt; FindLibraryLocationsByLibrary(int libraryId)
      {
          var result = new List&lt;LibraryLocation&gt;();
  
          var bookHoldings = (from bh in db.BookHoldings
                              where bh.LibraryId == libraryId
                              select bh).Select(x =&gt; x.LocationName).Distinct();
  
          var journalHoldings = (from jh in db.JournalHoldings
                                 where jh.LibraryId == libraryId
                                 select jh).Select(x =&gt; x.LocationName).Distinct();
  
          // TODO: Improve this by cleaning up three loops below?
  
          // Add common items
          foreach (var item in await bookHoldings.Intersect(journalHoldings).ToListAsync())
          {
              result.Add(new LibraryLocation { HoldingType = "BOTH", LibraryLocationName = item });
          }
  
          // Add book items
          foreach (var item in await bookHoldings.Except(journalHoldings).ToListAsync())
          {
              result.Add(new LibraryLocation { HoldingType = "BOOK", LibraryLocationName = item });
          }
  
          // Add journal items
          foreach (var item in await journalHoldings.Except(bookHoldings).ToListAsync())
          {
              result.Add(new LibraryLocation { HoldingType = "JOURNAL", LibraryLocationName = item });
          }
  
          return result;
      }
  }
  </code></pre>