Posts Tagged ‘linq’

VB.Net and lambda

November 30th, 2011

Using the terse lambda syntax used in C# also in VB.Net is also (almost) possible.

Here is a short example:

var nameList =
 where( x => x.ID = 42 ).
 select( x => x.Name ).

which in VBNet becomes:

Dim nameList =
 Where( Function(x) x.ID = 42 ).
 Select( Function(x) x.Name ).

Note that the periods have to be at the end of the line, otherwise the multi line capability of Vbnet doesn’t work.  This can be remedied by the old trailing underscore of VB.

If you need to set the type of x it is also doable:

Dim nameList =
 Where( Function(x As MyClass) x.ID = 42 ).
 Select( Function(x As MyClass) x.Name ).

Exception: Only parameterless constructors and initializers are supported in LINQ to Entities.

October 30th, 2010

I am not sure of the *exact* meaning and reason for this but I found something that can be good to know.  Or not.

return context.NuggetSet.Where(n => n.Name == name).Select(x => new MyClass(x)).ToList();

threw a

Only parameterless constructors and initializers are supported in LINQ to Entities.

When inserting a ToList it worked as suspected/wanted.

return context.NuggetSet.Where(n => n.Name == name).ToList().Select(x => new MyClass(x)).ToList();

My guess is that by calling ToList we losen EF’s grip of the entities and can do what we want with it.

List of lists and dictionaries in dotnet

June 2nd, 2010

Update: I wrote a longer article here.

List<T> is the work horse of list handling in dotnet.  But there are several more to choose from; ArrayList, Hashtable, SortedList, DictionaryEntry, ListDictionary, StringCollection, NameValueCollection, StringDictionary, HybridDictionary andOrderedDictionary for instance. Several of these are replaceable by generic lists so don’t memorise them.

Here is a link to a better explanation:

LINQ examples

March 22nd, 2009

Linq is sooo good.

The next time you loop a list or array to find a value or two; consider spending 15 minutes to learn some Linq; it is well invested.  The syntax is somewhat like SQL but more straight forward.  For instance the keywords are written “the normal” way.  First what you have (from), then the filtering (where) and finally what you want (select).

var query =
from c in myCustomerList
where c.Age < 42
select c;

If you are looping two lists and compare them to get a new list, you should really look into Linq.  It will save you lots of time.