Search code examples
c#icomparerstartswith

IComparer for string that checks if x starts with y


I've got an array of strings and I need to get all strings, that start with some 'prefix'. I wanna use Array.BinarySearch(). Is it possible? And how should I write a comparer if so?


Solution

  • No, you cannot use BinarySearch in this case. You could use Enumerable.Where instead:

    Dim query = From str In array Where str.StartsWith("prefix")
    

    or with (ugly in VB.NET) method synatx:

    query = array.Where(Function(str) str.StartsWith("prefix"))
    

    Edit: whoops, C#

    var query = array.Where(s => s.StartsWith("prefix"));
    

    Use ToArray if you want to create a new filtered array.