简体   繁体   中英

How to use a Linq Select Where from vb.net in C#?

I am converting an old vb.net application to C# and my VB Linq skills are lacking on many levels. I need this in C# linq:

  Dim dtx as New MyDataBaseContext(connectionString)
  Dim reports = new List(Of CustomerReport)

  reports = (From rpt In dtx.CustomerReports Join _
                           crs In dtx.Customer_Reports_Schedules On rpt.CRS_Key Equals crs.CRS_Key _
                           Where Not (crs.CRS_Occurrence.ToUpper.Contains("ADHOC") Or crs.CRS_Occurrence.ToUpper.Contains("OBSOLETE")) _
                           Select rpt Where rpt.Description.Contains(searchValue.Trim)).OrderBy(Function(p) p.Description).OrderBy(Function(p) p.CRS_Key).ToList

What I have so far converted is:

 reports = (from rpt in 
                _context.CustomerReports join crs in _context.Customer_Reports_Schedule on 
                rpt.CRS_Key equals crs.CRS_Key where !(crs.CRS_Occurrence.ToUpper().Contains("ADHOC")
                || crs.CRS_Occurrence.ToUpper().Contains("OBSOLETE"))
       //I am stuck here. I have not done a select where clause of this nature before
                select rpt where rpt.Description.Contains(request.Criterion.Trim())
       //I am also not completely sure what Function(p) does
                    .OrderBy(Function(p) p.Description).OrderBy(Function(p) p.CRS_Key)
                        .ToList());

As you can see there are two points in the linq that I am unsure of (see comments). I haven't seen this kind of select where clause in linq before (yes I googled it) and I have no idea what Function(p) is trying to do (I am googling it as we speak)

I think you want something like this although I can't test it completely obviously...

var likeString = string.Format("%{0}%", request.Criterion.Trim());

reports = (from rpt in 
                _context.CustomerReports join crs in _context.Customer_Reports_Schedule on 
                rpt.CRS_Key equals crs.CRS_Key where !(crs.CRS_Occurrence.ToUpper().Contains("ADHOC")
                || crs.CRS_Occurrence.ToUpper().Contains("OBSOLETE"))
       // SqlMethods.Like will give you the string.contains that I think this is doing
                select rpt where SqlMethods.Like(rpt.Description, likeString))
       // This becomes a lamda like Beakie & Chris mentioned...
                    .OrderBy(p => p.Description)
                        .ToList());

This uses a lambda for your OrderBy and SqlMethods.Like to replace your rpt.Description.Contains which should solve both parts of the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM