简体   繁体   English

如何通过在字符串数组中使用 LINQ 查询来获得多个匹配项?

[英]How to get multiple matches with using LINQ query in a string array?

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我有一个 function,它将“params string[] requested”作为输入,并且应该使用 readline 从用户那里获取输入并查看是否有任何匹配项,如果有任何匹配项则返回匹配项

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)"我得到的错误是“无法将类型‘System.Collections.Generic.IEnumerable’隐式转换为‘字符串’(csharp0029)”

I would prefer a solution that uses linq我更喜欢使用 linq 的解决方案

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). Where返回可枚举的匹配项(即使只有一个)。 FirstOrDefault will return the first one from the list or null if not found FirstOrDefault将返回列表中的第一个,如果找不到则返回 null

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鉴于FirstOrDefault采用可选谓词

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

Your method returns string but you return a kind of list inside of your method.您的方法返回string ,但您在方法内部返回一种列表。 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);
}


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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