LINQ 201 – Changing the way I work with lists

LINQ brings the set-based power of SQL-like syntax to VB.NET  and C#.  I thought I’d highlight some of the ways this has changed and simplified my code.

Find an element in a list

Pre-LINQ:
function FindItem(key as string)
  For each item in myList
    if item.Key = key then return item
  Next
end function
 
dim foundItem = FindItem(key)
if foundItem isnot nothing then
  ...process item
else
  ...not found
end if
Post-LINQ:
dim foundItems = from item in MyList where item.Key = key
if foundItems.Any then
  ...process item (foundItems.First)
else
  ...not found
end if

Find matching elements in a list

Pre-LINQ:
dim newList = new List(Of SomeClass)
for each item in oldList
  if item.SomeField = "Foo" then newList.Add(item)
next
Post-LINQ:
dim newList = from item in oldList where item.SomeField = "Foo"

Convert a list of items of one type into another

Pre-LINQ:
dim newList = new List(Of NewType)
for each item in oldList
  dim newItem = new NewType
  newItem.Field1 = item.FieldA
  newItem.Field2 = item.FieldB
 
  newList.Add(newItem)
next
Post-LINQ:
dim newList = from item in oldList _
  select new NewType with _
  {.Field1 = item.FieldA, _
   .Field2 = item.FieldB}

Sorting a list

Pre-LINQ:
Way too hard. Suffice to say it involved creating a new IComparer class or
implementing IComparable in the existing class
Post-LINQ:
dim sortedList = from item in myList _
  order by item.Field1

(or you could use lambda expression, but I find the above more readable)

Related Posts

Leave a Reply