fbpx
Welcome, Guest
Username: Password: Remember me
Share your code snippets, screen shots etc. here
  • Page:
  • 1

TOPIC: Another nice LINQ example

Another nice LINQ example 2 years 1 month ago #1

  • NickFriend
  • NickFriend's Avatar Topic Author
  • Offline
  • Posts: 167
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.
// 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.
// 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

Please Log in or Create an account to join the conversation.

Another nice LINQ example 2 years 1 month ago #2

  • Phil Hepburn
  • Phil Hepburn's Avatar
  • Offline
  • Posts: 737
  • Karma: 7
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 :-





Best regards,
Phil.
Wales, UK.
Attachments:

Please Log in or Create an account to join the conversation.

  • Page:
  • 1