Another nice LINQ example

Public forum to share code snippets, screen shorts, experiences, etc.
Post Reply
NickFriend
Posts: 248
Joined: Fri Oct 14, 2016 7:09 am

Another nice LINQ example

Post by NickFriend »

Following on from the recent discussion about the merits or otherwise of LINQ, I came across some more nice examples of how neat it is today whilst solving some coding problems. The code is in C# as I'm not confident that I'd get it correct in X#, but of course one of the advantages of X# is that basically if you can do it in C# you can do it in X# too.

The examples suppose we have a list of Order objects, each of which also has a property OrderItems which contain the list of items within each order.

Example 1 - find the order which contains the orderitem ID==10.

Code: Select all

// traditional
Order selectedorder = null;
foreach (Order order in orderlist)
{
  if (order.OrderItems != null)
  {
    foreach (OrderItem item in order.OrderItems)
    {
      if (item.OrderItemID == 10)
      {
        selectedorder = order;
        break;
      }
    }
    if (selectedorder != null)
      break;
  }
}

// LINQ
Order selectedorder = orderlist.Where(o => o.OrderItems.Any(i => i.OrderItemID == 10)).SingleOrDefault();
Example 2 - find the orderitem with ID==10.

Code: Select all

// traditional
OrderItem selecteditem;
foreach (Order order in orderlist)
{
  if (order.OrderItems != null)
  {
    foreach (OrderItem item in order.OrderItems)
    {
      if (item.OrderItemID == 10)
      {
        selecteditem = item;
        break;
      }
    }
    if (selecteditem != null)
      break;
  }
}

// LINQ
OrderItem selecteditem = orderlist.SelectMany(o => o.OrderItems).Where(i => i.OrderItemID == 10).SingleOrDefault();
I love it!

Nick
User avatar
Phil Hepburn
Posts: 743
Joined: Sun Sep 11, 2016 2:16 pm

Another nice LINQ example

Post by Phil Hepburn »

Hi Nick,

These nice simple examples of LINQ Extension Methods in action got me to look much more closely (in detail) into their use, and to make some other examples in X# syntax.

To wet guys appetites for these samples, here is a nice X# example of the 'let' clause in a query syntax line.

The let gives us a way to specify a variable in out query code line, and then re-use it. I have also used a static method or two in this code - we may need to be careful in using Methods in query LINQ code for L2S and L2E as the code needs to be able to be expressed in T-SQL script, so we can't just use any old .NET function/method.

More fun in the morning, first here are the 'let' images :-
NFreplyEMsLINQ_01.jpg
NFreplyEMsLINQ_01.jpg (50.8 KiB) Viewed 142 times
NFreplyEMsLINQ_02.jpg
NFreplyEMsLINQ_02.jpg (59.8 KiB) Viewed 142 times
Best regards,
Phil.
Wales, UK.
Post Reply