c# and Linq
by brian on Jan.28, 2008, under Uncategorized
Today I’ve been working at the usual problems of querying internal data model then flushing the changes out to an sqlite database. This is a real drag. I was going to clean up the class and make it more to my liking, so I went to add a new class when I noticed a ‘linq to sql’ option. Then it struck me that this must be something like automatic mapping of programming objects to database much like is had in ruby and rails. If so this would save me a ton of trouble
Well I started to dig. Wow! I’ve been programming for more than 20 years and had many different paradigm shifts. First of functional programming, object oriented programming, patterns, state machines and finite automota, standard template library, Borlands vcl libraries, and now I’m thinking linq is the next big paradigm shift.
I can remember many years ago wishing I’d had a way to do sql queries on my internal objects instead of a for loop over the list. Well I do know!!! Whoo hoo!! This is where the Linq technology comes in. Take a look at the following example:
public class Person
{
public int id;
public string firstName;
public string lastName;
public decimal cash;
public Person(int ID, string FirstName, string LastName, decimal Cash)
{
id = ID;
firstName = FirstName;
lastName = LastName;
cash = Cash;
}
}
....
List>person< people = new List>person<();
people.Add(new Person(1, "George", "McNommy",50));
people.Add( new Person(2,"Adam","Bobbly",1500));
people.Add( new Person(3,"Billy","Freddy",2212));
people.Add( new Person(4,"Caddice","Anderdotter",-34));
IEnumerable>string< result =
from person in people
orderby person.lastName
where person.cash > 0
select person.lastName+", "+person.firstName+": $"+person.cash.ToString();
foreach (string r in result)
log.Text += r + "\r\n";
And here the results as displayed in a rich edit box.
Bobbly, Adam: $1500 Freddy, Billy: $2212 McNommy, George: $50
I’m just scratching the surface here. This will make my life as a programmer so, so, so, much easier!!!
Thanks to Markus Egger for his article I’ve just begun reading and was so excited that I had to make a blog entry before I could finish the article. I sure there are more wonderful surprises coming.
Leave a Reply
You must be logged in to post a comment.
