For anyone experienced with linq, this will be a mundane post for you. But I was talking to a friend on twitter today about programming. I wanted
a short explanation of a problem and why linq is an awesome tool for dealing with lists/collections of data in the .NET framework.
So Imagine we have a list of objects called Stocks.
public class Stock
{
public string Ticker { get; set; }
public float Bid { get; set; }
public float Ask { get; set; }
public string Exchange { get; set; }
}
And let’s say we want to loop through them and do something special with stocks that are traded on the Nasdaq. The traditional way with an array to do this is the following:
for (int i = 0; i < stockList.Length - 1; i++)
{
Stock s = stockList[i];
if (s.Exchange.Equals("Nasdaq"))
{
CalculateFancyStatistic(s);
}
}
The foreach keyword in c# makes this slightly easier to do away with the for loop. So then we can right it like this.
foreach (Stock stock in stockList)
{
if (stock.Exchange.Equals("Nasdaq"))
{
CalculateFancyStatistic(stock);
}
}
This is definitely better, because you don’t have to worry about knowing how long the list is and only iterating that many times. The foreach operator takes care of that for you.
But now, behold the power of LINQ.
stockList.Where(stock=>stock.Exchange.Equals("Nasdaq"))
.ToList()
.ForEach(stock => CalculateFancyStatistic(stock));
That single statement replaces all of the above code, and does the exact same thing. If you really want to be concise you could also use something called a method group.
stockList.Where(stock=>stock.Exchange.Equals("Nasdaq"))
.ToList()
.ForEach(CalculateFancyStatistic);
And that my friends, is why c# is my all-time favorite language to program in. Gets the point across and lets you move on with your task!