如何根据用户输入从列表中提取

时间:2018-12-28 04:43:52

标签: c# .net linq sublist

代码包含两种方法。

  1. Main ,它会提示用户输入并根据所述用户输入来打印子列表。
  2. 提取 方法从用户输入传递 query 并将所有索引添加到dbQueryList中,以便从{{1}中提取}并打印为查询。

如何根据用户输入将其添加到dbListing中?

主要问题是 List语句,其中包含以下条件: if。这是为了测试条件“如果查询的一部分存在于i.Substring(0, query.Length) = query中的任何索引中,请向dbListing中添加元素”。

我最初是用Python编写的,它工作得很好。我正在学习C#,不确定如何更改该dbQueryList条件。我考虑过更改代码,并在if循环中使用LINQ,但对于如何实现它尚不完全清楚。

期待社区的反馈! :)


foreach

更新日期:2019年1/3/18:30

我对//************************************************** // File Name: autocomplete.cs // Version: 1.0 // Description: Create a method that functions like an autocomplete // API and truncates search to 5 results. // Last Modified: 12/19/2018 //************************************************** using System; using System.Collections.Generic; namespace autocomplete { class Program { private static string[] database; private static string input; private static string query; static void Main(string[] args) { // user input to pass as query Console.Write("Enter your query: "); string query = Console.ReadLine(); // dynamic list comprised of 'database' array List<string> dbListing = new List<string>(); string[] database = new string[] { "abracadara", "al", "alice", "alicia", "allen", "alter","altercation", "bob", "element", "ello", "eve", "evening", "event", "eventually", "mallory" }; dbListing.AddRange(database); // write results based on user query Console.WriteLine("Your results: " + Extract(Program.query)); // keep console window open after displaying results Console.ReadLine(); } // extract method passing query, return dbQueryList as query public static List<string> Extract(string query) { // empty list is initiated List<string> dbQueryList = new List<string>(); // foreach assesses all strings in database in main // then, appends all indices of list equal to given query foreach (string i in database) { // compares query (from index 0 to length of) to all strings in database if (i.Substring(0, query.Length) = query) { // add to list above based on query dbQueryList.Add(i); } // if statement truncates dbQueryList to 5 results if (dbQueryList.Capacity >= 5) break; } return dbQueryList; } } 进行了以下更改,并且有效!

Extract(query)

我为此感到非常兴奋!如果有必要,请告诉我有关如何改进和清理此代码的进一步反馈!大家加油!

1 个答案:

答案 0 :(得分:4)

问题是您在=语句中使用==而不是if

在C#中,=运算符用于赋值,因此您正在尝试将query赋给左侧的表达式,这是不可能的。而是使用==运算符进行比较。

还有一种更合适的方法-使用i.StartsWith(query)检查字符串是否以给定查询开头。只要i不小于query.Length,当前的解决方案就可以工作,在这种情况下,它将引发异常。

if (i.StartsWith(query))
{
   ...