【问题标题】:How to write like clause using LINQ in silverlight如何在silverlight中使用LINQ编写like子句
【发布时间】:2013-04-08 09:11:57
【问题描述】:

在我的项目中,我想对单元列表执行搜索操作。我有ObservableCollection<Unit> UnitList,其中包含使用 WCF 服务从 SQL Server 2008 获取的数据。我可以在 SQL Server 中使用 SQL Like 进行搜索,但为此我必须再次调用服务,这会影响性能。

为了解决这个问题,我现在尝试使用 LINQ 根据已获取的 ObservableCollection 上的搜索参数过滤数据。我写了以下查询:

 var result = from u in UnitList
                         where u.UnitNo.Contains(this.UnitNo)
                         && u.ParcelName.Contains(this.ParcelName)
                         && u.TransformationType.Contains(this.TransformationType)
                         && u.TenantName.Contains(this.TenantName)
                         && u.UnitType.Contains(this.UnitType)
                         && u.ClientContact.Contains(this.ClientContact)
                         select u;

但只有当所有参数都匹配时,它才会返回值。在 SQL Server 中,我使用 like '%%' 来解决
这个问题。如何在 LINQ 中编写。

编辑:我在 SO 的一个解决方案中找到了方法 SQLMethods.Like,但我无法在我的项目中使用此方法。我需要为此添加任何参考吗?

【问题讨论】:

  • 服务使用什么样的数据访问层? (linq to something?)我的意思是:你不能在服务调用中过滤吗?
  • 当然它会返回所有参数,因为您使用的是 && (AND) 条件。也许您需要我们||条件而不是 &&? Method Contains 的工作方式与 SQL server 中的 LIKE '%%' 完全相同。
  • @GertArnold 我想减少服务调用。我可以在服务调用中过滤数据。
  • @MichaelSamteladze 试过但没有运气

标签: linq silverlight-5.0 sql-like


【解决方案1】:

你可以使用:

List<Units> listUnits = UnitList.Where(d => d.UnitNo == this.UnitNo 
  && d.ParcelName == this.ParcelName 
  && d.TransformationType == this.TransformationType 
  && d.TenantName == this.TenantName 
  && d.UnitType == this.UnitType 
  && d.ClientContact == this.ClientContact ).Tolist();

这样,您将把 UnitList 中具有您的参数的所有单位放入 listUnits 中。

有关 Linq 的更多信息,请查看:

http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b

【讨论】:

    【解决方案2】:

    也许你是安装了不区分大小写参数的 sql server。 “包含”区分大小写。只需在您的字符串上使用 ToUpper 或 ToLower。

    【讨论】:

    • 我使用的是 LINQ 而不是 sql server。
    • 是的,但 c# 中的“包含”区分大小写。只需在您的字符串上使用 ToUpper 或 ToLower 即可。 (msdn.microsoft.com/en-us/library/dy85x1sa.aspx) u.ParcelName.ToLower().Contains(this.ParcelName.ToLower())
    猜你喜欢
    • 2012-12-05
    • 2022-01-13
    • 2012-05-31
    • 2017-01-12
    • 2013-11-25
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多