Another nice LINQ example
Posted: Fri Jan 27, 2017 3:03 pm
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.
Example 2 - find the orderitem with ID==10.
I love it!
Nick
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();
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();
Nick