tags:

views:

107

answers:

3

When I'm writing code, I'm starting to identify those places where I could use Linq. My problem is that I'm still very new to the syntax. I learn best through examples, but I can't seem to easily find the example I need.

I wanted to start this thread to create a repository of common Linq expressions that others could stumble upon via google.

The question: can you provide any examples of Linq expressions you use for common tasks?

For example, I've already written the following:

  • searching a list
  • summing an array
  • summing a certain property in a collection of elements

To get the thread started, I'll post an answer that contains these.

+8  A: 

101 Linq Samples for c#
http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

Robert Harvey
A: 

Enumerating through a list to find a certain element

tboShippingLotNumber existingLotNumber =
    (tboShippingLotNumber)(from lot in shipmentDetailLine.LotNumbers
                           where 
                               (lot.LotNumber == lotNumber) &&
                               (lot.ShipLineKey == shipmentDetailLine.Key)
                           select lot).ElementAtOrDefault(0);

if (existingLotNumber == null)
{
    // not found exception
}

Summing an array:

decimal[] array = { 1.5m, 2.5m, 3.5m };
decimal sum = array.Sum();

Summing a certain property in a list of objects

decimal sum = (from shipment in _ShipmentData.Shipments select 
    shipment.AmountShipped).Sum()
Robert H.
A: 

You could always browse the LINQ questions on StackOverflow.

Winston Smith