LIKE operator in LINQ

前端 未结 14 1118
一生所求
一生所求 2020-11-27 16:29

Is there any way to compare strings in a C# LINQ expression similar to SQL\'s LIKE operator?

Suppose I have a string list. On this list I want to search

14条回答
  •  借酒劲吻你
    2020-11-27 16:56

    As Jon Skeet and Marc Gravell already mentioned, you can simple take a contains condition. But in case of your like query, it's very dangerous to take a Single() statement, because that implies that you only find 1 result. In case of more results, you'll receive a nice exception :)

    So I would prefer using FirstOrDefault() instead of Single():

    var first = Database.DischargePorts.FirstOrDefault(p => p.PortName.Contains("BALTIMORE"));
    var portcode = first != null ? first.PortCode : string.Empty;
    

提交回复
热议问题