user1202606
user1202606

Reputation: 1160

c# lambda expression convert from vb to c#

I'm trying to convert this vb.net code to c#.

        If (txtCompanyName.Text.Trim() <> String.Empty) Then
            decals = decals.Where(Function(d As CT_Decal) (From c In db.CT_Companies Where c.CompanyName.Contains(txtCompanyName.Text.Trim()) Select c.CompanyID).ToList.Contains((From t In db.CT_Tanks Where t.CargoTankID = d.TankID Select t.CompanyID).Single.ToString()))
        End If

In c# I tried to put the code:

        if (txtCompanyName.Text.Trim() != string.Empty)
        {
                    decals = decals.Where(Function(CT_Decal d)(from c in db.CT_Companies 
                                                where c.CompanyName.Contains(txtCompanyName.Text.Trim())
                                                select c.CompanyID).ToList().Contains((from t in db.CT_Tanks                                                                                                    where t.CargoTankID == d.TankID 
                                                select t.CompanyID).Single.ToString()));

        }//end if

c# errors:

The name function does not exist and CT_Decal is a type but is used like a variable.

Does anybody know how to convert this properly?

Upvotes: 0

Views: 182

Answers (2)

jessehouwing
jessehouwing

Reputation: 114491

Without access to your DBContext it's hard to give you an exact query, ignoring the inefficiency of the query you're using.

From what we have, I expect the following code gets pretty close to what you want, or at least should get you started:

        if (!String.IsNullOrWhiteSpace(txtCompanyName.Text))
        {
            var result = 
                decals.Where(
                    d => (
                        from c in db.CT_Companies 
                            where c.CompanyName.Contains(txtCompanyName.Text.Trim()) 
                            select c.CompanyID
                    ).Contains(
                        (from t in db.CT_Tanks where t.CargoTankID == d.TankID select t.CompanyID).Single()));

I expect this will function exactly the same if you've setup your DBContext correctly:

        if (!String.IsNullOrWhiteSpace(txtCompanyName.Text))
        {
            IEnumerable<Decal> result = 
                decals.Where(d => string.Equals(d.Tank.Company.CompanyName, txtCompanyName.Text.Trim());

Upvotes: 2

AlwaysAProgrammer
AlwaysAProgrammer

Reputation: 2919

your problem is in the keyword function within the where clause.

You must write something like this .Where(d=>(....)). Please see 'jessehouwing' reply.

The syntax .Where(function(f) ....) is a VB.Net equivalent of the lambda expression in C#. The lambda expression .Where(d => (...)) means 'd' goes to (some action or expression ). Let me know if this helps.

Upvotes: 0

Related Questions