简体   繁体   中英

Display array after selecting with linq

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);
    } 

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));
private static void DisplayArray(IEnumerable<string> array)
{
    foreach (string item in array)
       Console.WriteLine(item);
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM