Lambda Coding - Basic Code Of Lambda With Explanation
Jun 21, 2011Im hearing about this, can someone explain it to me or please show some basic code of Lambda with explanation.
View 2 RepliesIm hearing about this, can someone explain it to me or please show some basic code of Lambda with explanation.
View 2 RepliesIs it possible to shorten the following function to a lambda expression?Or (to do the trick by myself) what is the best and most understandable for beginners tutorial for lambda in vb.net?[code]
View 2 RepliesConsider the following C# code:
private void SomeMethod()
{
IsBusy = true;
var bg = new BackgroundWorker();
bg.DoWork += (sender, e) =>
[code]....
However, I'd like to be able to implement a method like SomeMethod from the C# example in VB.net. Likely this means wrapping the Backgroundworker in another class (which is something I want to do for dependency injection and unit testing anyway).
I am dumb founded at this statement....maybe its just too many hours/days of doing C# to VB.Net conversion but i am drawing a blank on this conversion.
List<string> sColors = new List<string>(this.CustomPaletteValues.Split(','));
try {
List<Color> colors = sColors.ConvertAll<Color>(s => (Color)(new ColorConverter().ConvertFromString(s)));
What i have so far:
Dim colors As List(Of Color) = sColors.ConvertAll(Of Color)(....)
As you can see its the content of the lambda that i am hitting a brick wall with.
I see lambda expressions have become a very useful tool at some points in the language. I've been using them a lot and most of the time they fit really nice and make the code shorter and perhaps clearer.
Now.. I've seen some , I would say excessive use of them. Some people like them so much that try to use them everywhere they can.. Some times the C# code looks like a functional language. Other factors against are the cost using reflection by lambda and that not friendly to debugging.I would like to hear opinions about how good and how code clear it is to use more or less the lambda expressions. (this is not the better example, but let's say it was the trigger)I was writing the following code. The use of the delegate { return null; } helps me avoid having to ask if the event is null or not every time I have to use it.
public delegate ContactCellInfo.Guest AddGuest();
public event AddGuest GuestRequest = delegate { return null;}
Im using resharper and the wise resharper( even it some times literaly eats the memory) made me the following suggestion
public delegate ContactCellInfo.Guest AddGuest();
public event AddGuest GuestRequest = () => null;
At my point of view the code using the delegate looks clearer. I am not against the Lamdba expression just would like to hear some advices on how and when to use them.
I have been looking at certain tutorials on sharparchitecture and trying to no avail (the online convertors don't seem to be able to do this):
private Action<AutoMappingExpressions> GetSetup()
{
return c =>
[Code].....
converting this to VB.NET
public void GetCustomers(Action<IEnumerable<Customer>> onSuccess, Action<Exception> onFail)
{
Manager.Customers.ExecuteAsync(op =>
{
[code]....
How would I translate this C# lambda expression into VB.NET ?query.ExecuteAsync(op => op.Results.ForEach(Employees.Add));
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
[Code]...
I have recreated the Predicatebuilder class in a seperate C# project and I'm trying to use it in a VB.NET project but I keep getting the following error: Overload resolution failed because no accessible 'Or' accepts this number of arguments.when I use it like so:
Dim predicate = PredicateBuilder.False(Of t_Quote)()
predicate = predicate.Or(Function(q) q.iQuoteType = iQuoteType)
The relivant project is referenced, I'm using the correct imports statement and it all compiles without any errors.
[Code]...
Functionally, is there any difference (apart from syntax onbviously) between lambda expressions in C# and VB.Net?EDIT: following up on CraigTP's answer: any references to the situation in .Net 4?EDIT: I'm asking because I'm used to C#, but for a next project the customer asks VB.Net. We're not a priori against that. We realize that most language constructs are supported in both languages. However, we're particularly fond of the way C# implements lambda expressions. We would like to have an overview of the differences with VB.Net
EDIT: accepted CraigTP's answer for pointing out what I currently consider the most important difference.
So to summarize: VB.Net 9 does not support multiline statements in a lambda expression, and a lambda must always return a value. Both of these issues are addressed in VB.Net 10
In looking at Fuzzy Date Time Picker Control in C# .NET? Piotr Czaapla's answer to that question is exactly what I need. unfortunately, I'm a VB.NET guy and I'm not that familiar with lambda expresions, so my attempts to convert the code have resulted in hours of misplaced parenthesis and banging my head with a brick.
Any chance some bi-lingual wizard could convert the C# code to VB.net for me?
[Code]...
Using lambda's in VB.Net results in no intellisense. Is this a bug with VS2010 or expected? Note that it works fine in C#
Return Array.TrueForAll(chequeColl, Function(x) x.Number <> "N") 'No intellisense Number does not appear
Return Array.TrueForAll(chequeColl, Function(x As MyClass) x.Number <> "N") 'Now casted intellisense appears
UPDATE: Here's an example
Public Class Cheque
Public Property Id As String
Public Property Status As Byte
[code]....
Async Sub like this: Dim f As Func(Of Task) = Async Sub() End Sub Produces compiler error: error BC36670: Nested sub does not have a signature that is compatible with delegate 'System.Func(Of System.Threading.Tasks.Task)'.Equivalent C# code compiles fine:
Func<Task> f = async () => { };Rewriting Async Sub into Async Function make code works.
Why does Async Sub() is not convertible to delegate types with return value of type Task?
How should the following C# code be converted to VB.Net? I have tried several code converters and none produce correct results.
[code]...
I have this function that maps a IDataReader to a class. It is obviously written in C#. My co-worker wants to use the same method in his code, but he is writing in VB.net. Basically I am having difficulty rewriting this due to the Lambda expressions used in C#. He is running .Net 3.5.
[Code]...
I will probably sound like a bad developer here, but I am attempting to convert some code from the following page from C# to VB.NET:The code I am having trouble converting is from Step 4 of "Joining a Multicast Group" on the page, and here is the code with the comment lines removed:
private void Join()
{
_receiveBuffer = new byte[MAX_MESSAGE_SIZE];
[code].....
how to convert this code to VB.net, can anybody help?
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached(
"Command",
[code]...
I want to implement this function:
Public Function GetFunc(Of TSource, TResult) _
selector As Expression(Of Func(Of TSource, TResult)) _
As Func(Of TSource, TResult)
[code]....
UPDATE:I have the following issue, it's a part of a function:
Dim obj As Object = value
For Each exp In expressions
If obj Is Nothing Then Return [default]
[code]....
Exception Details:
ArgumentException:Object of type 'System.Linq.Expressions.Expression`1 [System.Func`3[System.Char,System.Char,System.Char]]'cannot be converted to type 'System.Func`3[System.Char,System.Char,System.Char]'.
Is it possible to create anonymous delegates in vb.net version 8 or earlier? If so, could someone provide an example of the syntax?
View 2 RepliesIf been try to convert some code I have from VB.net to C# but I just cannot get it working!first is the vb code I'm only interested in the line that has the Lambda Expression for the C#[code]......
View 2 RepliesCurrently, I have code similar to this:
xxx, _
If(dr.Table.Columns.Contains("EnterpriseID"), dr.Field(Of Integer)("EnterpriseID"), -1), _
xxx
I would like to create a Lamdba expression something like the following (this doesn't work):
Dim xCol As Func(Of DataRow, String, Type, Object, Object) = _
Function(dr, x, t, dflt) _
If(dr.Table.Columns.Contains(x), dr.field(Of t)(x), dflt)
So that I can say something like:
xxx, _
xCol(dr, "EnterpriseID", GetType(System.Integer), -1), _
xxx
I have the following array
Dim items() = {
New CheckedListBoxItem("NYC", False),
New CheckedListBoxItem("CHI", False),
New CheckedListBoxItem("PHL", False),
New CheckedListBoxItem("SFO", False),
}
I am trying to query against it like this
Try
Dim item As CheckedListBoxItem = items.ToList().Where(Function(x) x.Value = "PHL")
MsgBox(item.Value)
Catch ex As Exception
MsgBox(ex.Message)
End Try
I am getting the error
Value cannot be null.
Parameter name: source
I also tried
Dim item As CheckedListBoxItem = items.FirstOrDefault(Function(x) x.Value.ToString() = "PHL")
I just need to query against the list to get an item and change it's checkedstate from false to true.
I have a List(of T) where T has a property that is a list of checkboxes, what I need is a Lambda expression that will count all the checked checkboxes in the list. I tried with:
[Code]...
I know in VB Lambda expressions must return a value and can only have one statement. But in my case I just need to execute a Sub that does not return a value. Is there a way to trick it by somehow returning a dummy value yet still call my Sub? If possible what would the syntax be like?
View 3 RepliesI am having an issue using the vb equivilant of the MAX lambda expression. at foos.Max(function(x) x.id) when I try to intellisense the property ID VS will not show it. But when i run the example it works. Is there something I am doing which is wrong, an i am just lucky it runs? [Code]
View 1 RepliesThere is the code:
Private Sub InsertItemInCache(Of T)(ByVal item As CachedItem(Of T), ByVal dependency As AggregateCacheDependency, _
ByVal key As String, ByVal updateCallBack As CacheItemUpdateCallback)
[code].....
This code is supposed to return all the records where the month component of the DateCreated is equal to the specified MonthIssued value. The problem is, if DateCreated is DBNull I will get a runtime exception which requires the extra If ternary operator. Any way around this / will this cause a performance hit the code is actually executed?
[code]...
I've created the following recursive lambda expression that will not compile, giving the error
Type of 'OpenGlobal' cannot be inferred from an expression containing 'OpenGlobal'.
Dim OpenGlobal = Sub(Catalog As String, Name As String)
[Code].....
I just came across a bug in NHibernate which happens to already be raised: [url] I'm not sure if this applies to anything else other than enums but when using a Lambda from VB, it looks different to the same Lambda from C#.
C#:
Where(x => x.Status == EmployeeStatus.Active)
VB
Where(Function(x) x.Status = EmployeeStatus.Active)
They are the same as far as I'm aware? (My VB isn't great) If I put a break point on the same line of code, where the above code is passed into. In C# I get: On the same line when VB version is passed in, I get: Is this something I'm doing wrong? Is the result's the same, just displayed different between C#/VB?
Edit: Ok so they are displayed different, but they can't be the same because NHibernate cannot handle it. The C# version is handled perfectly fine by NHibernate, the VB version resolves in the following exception being thrown: [Code]
I finally found out that my lambda in the following statement evaluates to false as opposed to the corrected version. Just wondering why:
CODE: