Home > Mobile >  Issues with using LINQ .where/.select in strings
Issues with using LINQ .where/.select in strings

Time:04-13

I have a function that takes "params string[] requested" as input and is supposed to use readline to get input from the user and see if any match and if anything matches then return what matches

static string inputCheck(params string[] requested){
    string? userInput = Console.ReadLine();
    IEnumerable<string> selected = requested.Where(n => n == userInput);  
    if (selected != null) return selected; //Error is here
    return "Nothing Please Try again";
}

The error I get is "Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'string' (csharp0029)"

I would prefer a solution that uses linq

CodePudding user response:

Your method returns string but you return a kind of list inside of your method. Solution:


    public static List<string> InputCheck(params string[] requested)
    {
        Console.Write("search: ");
        var userInput = Console.ReadLine();
        var filteredList = requested
            .Where(n => n == userInput)
            .ToList();

        return filteredList;
    }

..so you can call the method like this:


var yourArray = new[]
{
    "lorem",
    "ipsum",
    "dolor",
    "sit",
    "amet",
    "lorem",
    "ipsum",
    "dolor",
    "sit",
    "amet"
};

var results = YourClass.InputCheck(yourArray);

if(results.Any())
{ 
   foreach (var result in results)
      Console.WriteLine(result);
}


CodePudding user response:

You need

static string inputCheck(params string[] requested){
    string? userInput = Console.ReadLine();
    var selected = requested.Where(n => n == userInput).FirstOrDefault(); <<<<===
    if (selected != null) return selected; //Error is here
    return "Nothing Please Try again";
}

Why? Where returns an enumerable of the matches (even if there is only one). FirstOrDefault will return the first one from the list or null if not found

Or even

static string inputCheck(params string[] requested){
    string? userInput = Console.ReadLine();
    var selected = requested.FirstOrDefault(n => n == userInput);  
    if (selected != null) return selected; //Error is here
    return "Nothing Please Try again";
}

given that FirstOrDefault takes an optional predicate

another alternative was

static string inputCheck(params string[] requested){
    string? userInput = Console.ReadLine();
    var selected = requested.Where(n => n == userInput);  
    if (selected.Any()) return selected.First(); 
    return "Nothing Please Try again";
}
  • Related