priyanka.sarkar priyanka.sarkar - 15 days ago 17
C# Question

A better implementation of LINQ Query to find the distinct prefixes

Given a list of words and a length, we need to find out the distinct prefixes of those words specified by the length.

e.g.

static void Main(string[] args)
{
foreach (var p in Prefixes(new string[] { "many", "manly", "men","maybe", "my" }, 3))
{
Console.WriteLine(p);
}

Console.ReadKey();
}

public static IEnumerable<string> Prefixes(IEnumerable<string> words, int length)
{
return words
.TakeWhile(w => w.Length >= length)
.Select(word => word.Substring(0, length))
.Distinct()
.OrderBy(o => o);
}



Output
--------
man
may
men



Any better implementation using LINQ?

Answer

Replace TakeWhile with Where because if TakeWhile will stop when it encounters the first non-match. But Where will look into the whole sequence for matches.

If { "many", "ma", "men","maybe", "my" } will be passed.

Then TakeWhile will give : man

But Where will give all the matches.

So the query will be:

public static IEnumerable<string> Prefixes(IEnumerable<string> words, int length)
{
    return words
     .Where(w => w.Length >= length)
     .Select(word => word.Substring(0, length))
     .Distinct()
     .OrderBy(o => o);          
}

TakeWhile vs Where