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 =
 myFacade.GetData().
 where( x => x.ID = 42 ).
 select( x => x.Name ).
 ToList();

which in VBNet becomes:

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

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 =
 myFacade.GetData().
 Where( Function(x As MyClass) x.ID = 42 ).
 Select( Function(x As MyClass) x.Name ).
 ToList()

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: http://www.platinumbay.com/blogs/dotneticated/archive/2007/06/08/hashtables-and-stacks-and-linkedlists-oh-my.aspx

*Update*: I wrote some more, and later, info here.

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.