如何编写CompareTo方法以比较二进制搜索算法中的字符串值

问题描述 投票:0回答:1

我正在使用c尖锐。我有一个排序列表,其中包含一些值,例如名称和数量。

我的代码:

using System;
using System.Collections.Generic;
using static System.Console;
namespace InventoryManagementSystem
{
    public class Tool
    {


            public Tool(string name, int quantity)
            {
                this.Name = name;
                this.Quantity = quantity;
            }

            public string Name { get; }
            public int Quantity { get; }


        public  int CompareTo(SortedList<string, Tool> other, String name)
        {
            return; //not sure how to write this properly
        }
    }
}

// toolitems类

 public class ToolItems

    {


        SortedList<string, Tool> gardeningTools = new SortedList<string, Tool>();

 public void gardeningToolData()
        {
            Tool gardeningTool1 = new Tool("Garden gloves", 50);
            gardeningTools.Add(gardeningTool1.Name, gardeningTool1);

                    WriteLine("Please enter a name of the tool");
                    String user = ReadLine();
                    int number = binarySearch(user);
}

        public int binarySearch(String user)
        {
            int high, mid, low;
            high = gardeningTools.Count - 1;

            WriteLine("inside bianry");
            WriteLine(gardeningTools.Values[0].Quantity);

            low = 0;
            if (gardeningTools.Values[high].Name.Equals(user))
                return 0;
            else if (gardeningTools.Values[high].Name.Equals(user))
                return high;
            else
            {
                 while (low <= high)
                 {
                     mid = (high + low) / 2;
                     if (Tool.CompareTo(gardeningTools.Values[high].Name, user) == 0) //here not sure how to compare the values as my compareTo method is not right
                         return mid;
                     else if (CompareTo(gardeningTools.Values, user) > 0)
                         high = mid - 1;
                     else
                         low = mid + 1;

            }
            return -1;

        }

我的问题是如何编写CompareTo()方法,这样我就可以比较两个值并检查sortedList中的用户值是否匹配,如果是,我想根据用户借入的数量来更新数量值。我不是能够写CompareTo()方法,而我写的(CompareTo())方法是错误的。谁能帮我吗?

简而言之,我要做的就是当用户输入某个字符串值,并且如果它在sortedlist中匹配(我们使用二进制搜索算法进行搜索),我们将从排序后的列表中获取该值的索引并更新该特定值的数量值(如果用户选择'A'并且它在索引0(“ A”,5)处,则我们询问用户您要借多少A并说2,因此数量现在更新为3。) >

我正在使用c尖锐。我有一个排序列表,其中包含一些值,例如名称和数量。我的代码:使用系统;使用System.Collections.Generic;使用静态System.Console;名称空间...

c# list binary-search compareto sortedlist
1个回答
0
投票

SortedList正在实现IDictionary。基本上,您的排序列表将具有IDictionary拥有的方法。您可以检出此链接Microsoft Docs SortedList

© www.soinside.com 2019 - 2024. All rights reserved.