如何在c#中使用Linq Select from vb.net

本文关键字:Select Linq from vb net | 更新日期: 2023-09-27 18:13:26

我正在将一个旧的vb.net应用程序转换为c#,我的VB Linq技能在许多层面上都缺乏。我需要在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

我目前转换的是:

 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());

正如你所看到的,linq中有两点我不确定(见注释)。我之前没有在linq中见过这种select where子句(是的,我搜索过),我不知道Function(p)要做什么(我正在搜索它,因为我们说话)

如何在c#中使用Linq Select from vb.net

我认为你想要这样的东西,尽管我不能完全测试它…

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());

这使用一个lambda为您的OrderBySqlMethods.Like来代替您的rpt.Description.Contains,这应该解决这两个部分的问题。