从用户输入中搜索列表中的特定元素

时间:2016-03-28 23:07:22

标签: c#

我有一个包含元素的列表。用户应该能够搜索特定元素和列表。然后列表应打印出包含此特定元素的所有行。为什么这不起作用?

 Car search = new Car();
 public void SearchLog()
    {

        for (int i = 0; i < myList.Count; i++)
        {

            if (myList[i].Model== search.Model)
            {
                Console.WriteLine("Model :" + search.Model)

            }
        }
    }
Console.Write("Search for model:");
search.searchModel = Console.ReadLine();

现在正在运作!总是需要学习的东西。问题是我的类变量。所以我使用相同范围的变量。

1 个答案:

答案 0 :(得分:1)

我根据问题和评论中的信息为您提供完整的代码:

这将是Car的样本类;

class Car
    {
        public string Model { get; set; }
        public string Name { get; set; }
        public string Brand { get; set; }
        //Rest of properties here
        public override string ToString()
        {
            string output = String.Format("Model :{0} \n Name :{1} \n Brand :{2}", this.Model, this.Name, this.Brand);
            return output;
        }
    }

以下是执行操作的主要功能:

public static List<Car> myList = new List<Car>();
static void Main(string[] args)
        {
            myList.Add(new Car() { Model = "A", Name = "XXX", Brand = "Some Brand" });
            myList.Add(new Car() { Model = "B", Name = "YYY", Brand = "Some Brand1" });
            myList.Add(new Car() { Model = "C", Name = "ZZZ", Brand = "Some Brand2" });
            Car search = new Car();
            Console.Write("Search for model:");
            search.Model = Console.ReadLine();
            Console.WriteLine("Following Result Found for {0}", search.Model);
            SearchLog(search);
       }

最后SearchLog的签名是:

public static void SearchLog(Car search)
        {
            var resultList = myList.Where(x => x.Model == search.Model).ToList();
            int i = 1;
            foreach (var car in resultList)
            {
                Console.WriteLine("Result {0} : {1}", i++, myList[i].ToString());
            }
        }

我有另一个建议;搜索不必是类Car的对象。它可以是字符串;

您可以按照以下方式尝试:

 Console.Write("Search for model:");
 string inputSearch = Console.ReadLine();
 bool carFound = false;
 for (int i = 0; i < myList.Count; i++)
   {
     if (myList[i].Model == inputSearch)
        {
           Console.WriteLine("Model: " + myList[i].Model);
           carFound = true;
        }
   }
  if (!carFound) { Console.WriteLine("None model were found"); }