LIKE operator in LINQ

前端 未结 14 1106
一生所求
一生所求 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:42

    Typically you use String.StartsWith/EndsWith/Contains. For example:

    var portCode = Database.DischargePorts
                           .Where(p => p.PortName.Contains("BALTIMORE"))
                           .Single()
                           .PortCode;
    

    I don't know if there's a way of doing proper regular expressions via LINQ to SQL though. (Note that it really does depend on which provider you're using - it would be fine in LINQ to Objects; it's a matter of whether the provider can convert the call into its native query format, e.g. SQL.)

    EDIT: As BitKFu says, Single should be used when you expect exactly one result - when it's an error for that not to be the case. Options of SingleOrDefault, FirstOrDefault or First should be used depending on exactly what's expected.

提交回复
热议问题