0

I'm trying to list all the words with 4 letters. But I'm not sure why it's not working. It will not display it.

This is the code:

    IEnumerable<string> query4 = words
       .Where(n => n.Length == 4)
       .Select(n => n);

    DisplayArray(query4);

This is my display method:

    private static void DisplayArray<T>(T[] array)
    {
        foreach (T item in array)
            Console.WriteLine(item);
    } 
3
  • 2
    For starters query4 isn't an array. Either change your method to take IEnumerable<T> or use ToArray. Commented May 12, 2016 at 13:25
  • Thank's. I'am knew in linq. I thoat it beaves like an array Commented May 12, 2016 at 13:29
  • 1
    Nope, an array is a structure that contains a set of values where as a Linq query produces an IEnumerable<T> that only represents a sequence that is not set and you have to materialize it by using a foreach or ToList or ToArray. Until then it doesn't actually do the filtering or projecting. Also it will do the filtering and projecting each time you materialize it. That's why you'll see a lot of Linq queries ending with a ToList. Commented May 12, 2016 at 13:37

2 Answers 2

2

Well, according to your current code

  private static void DisplayArray<T>(T[] array)

wants array T[] but you provide just IEnumerable<string> and so you should have a compile time error. Change T[] to IEnumrable<T>:

  // you have no need in T[], IEnumerable<T> is quite enough
  private static void DisplayArray<T>(IEnumerable<T> array) {
    foreach (T item in array)
      Console.WriteLine(item);
  }

Finally (please, notice that Select(n => n) is redundant and can be dropped):

  DisplayArray(words.Where(n => n.Length == 4));
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the answer! It helped.
How can I make a method that will be good for array and for IEnumerable?
@sara: T[] (array) implements IEnumerable<T> so if you've implemented a method for IEnumerable<T> it will do for array T[]; the reverse is not true
0
private static void DisplayArray(IEnumerable<string> array)
{
    foreach (string item in array)
       Console.WriteLine(item);
} 

2 Comments

It may appear that you narrow down DisplayArray method too hard; what if another Linq returns IEnumerable<int>?
as your provide IEnumerable<string> that why I use that. Thanks for your advice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.