简体   繁体   English

具有通用方法的线性搜索算法

[英]Linear search algorithm with generic methods

I have a problem with code.我的代码有问题。 I receive an error CS0311: The type 'object' cannot be used as type parameter 'T' in the generic type or method 'GenericMethods.search(T[], T)'.我收到错误 CS0311:类型 'object' 不能用作泛型类型或方法 'GenericMethods.search(T[], T)' 中的类型参数 'T'。 There is no implicit reference conversion from 'object' to 'System.IComparable'.没有从“object”到“System.IComparable”的隐式引用转换。

Task: Create a console app and write a generic method, Search [ int Search( T [ ] dataArray, T searchKey) ] that searches an array using linear search algorithm.任务:创建一个控制台应用程序并编写一个通用方法 Search [ int Search( T [ ] dataArray, T searchKey) ],该方法使用线性搜索算法搜索一个数组。

a) Method Search should compare the search key with each element in the array until the search key is found or until the end of the array is reached. a) 方法搜索应将搜索关键字与数组中的每个元素进行比较,直到找到搜索关键字或到达数组末尾。

b) If the search key is found, return/display its location in the array (ie its index value); b) 如果找到了搜索键,则返回/显示它在数组中的位置(即它的索引值); otherwise return -1.否则返回-1。

c) You need to populate the array with random values. c)您需要使用随机值填充数组。 ( int values – between 10 and 49, double values between 50 and 99, char values between a and z). ( int 值 - 10 到 49 之间,double 值介于 50 和 99 之间,char 值介于 a 和 z 之间)。 The size of array as 10.数组的大小为 10。

d) Test this method by passing two types of arrays to it. d) 通过将两种类型的数组传递给它来测试这个方法。 (an integer array and a string array) Display the generated values so that the user knows what values he/she can search for. (整数数组和字符串数组)显示生成的值,以便用户知道他/她可以搜索哪些值。

[Hint: use (T: IComparable) in the where clause for method Search so that you can use method CompareTo() to compare the search key to the elements in the array] [提示:在方法 Search 的 where 子句中使用 (T: IComparable),以便您可以使用方法 CompareTo() 将搜索键与数组中的元素进行比较]

My code:我的代码:

using System;使用系统;

using System.Collections.Generic;使用 System.Collections.Generic;

namespace LinearSearch { class GenericMethods {命名空间线性搜索 { 类 GenericMethods {

    static void Main(string[] args)
    {

        object[] dataArray = new object[10];
        Random random = new Random();

        for (int i = 0; i < dataArray.Length; i++)
        {
            int randomType = random.Next(1, 3);


            if (randomType == 1)


            {

                char randomChar = (char)random.Next('a', 'z');
                dataArray[i] = randomChar;


            }

            else if (randomType == 2)
            {


                double randomDouble = random.Next(50, 99);
                dataArray[i] = (int)randomDouble;
            }

            else
            {


                int randomInt = random.Next(10, 49);

                dataArray[i] = randomInt;


            }

        }

        Console.WriteLine("Generated array is: ");
        Console.WriteLine(string.Join(" ", dataArray));
       
       

        Console.WriteLine("Please, enter number from 10 to 99 or char from A to Z");
        object  userInput = Console.ReadLine();
        Console.WriteLine(userInput);
        Console.WriteLine($"Location of search value {userInput}: {search(dataArray, userInput)}");



    }//end Main method


    private static int search<T>(T[] dataArray, T searchKey) where T : IComparable<T>
    {
        // default to -1 so that we can determine the search is successful when it becomes a positive value
        int arrayPosition = -1;
        for (int x = 0; x < dataArray.Length; x++)
        {
            T arrayElement = dataArray[x];
            // Console.WriteLine($"CompareTo result: {searchValue.CompareTo(arrayElement)}");
            if (searchKey.CompareTo(arrayElement) == 0)
            {
                // value is found
                arrayPosition = x;
                break;
            }
        }
        return arrayPosition;
    } // end searchValue




}
}

Could you please help me to fix this problem?你能帮我解决这个问题吗? I am new in C#..我是 C# 的新手..

Instead of declaring dataArray as an object[] declare it as an IComparable[] .与其将dataArray声明为object[] ,不如将其声明为IComparable[] You wrote the type constraint limiting your generic type T to IComparable .您编写了将泛型类型T限制为IComparable的类型约束。 object does not implement IComparable , so it is not a valid type object未实现IComparable ,因此它不是有效类型

Lucky me, I always write generic searches for my code.幸运的是,我总是为我的代码编写通用搜索。 For other search methods with Generics in C#, you can find them here .对于 C# 中使用泛型的其他搜索方法,您可以在此处找到它们。

public static int LinearSearch<T>(T[] array, T item) // O(n)
{
    for (int i = 0; i < array.Length; i++)
        /* array[i] == item */
        if (Comparer<T>.Default.Compare(array[i], item) == 0)
            return i;

    return -1; // Not found
}

You must import 'System.Collections.Generic' in your file.您必须在文件中导入“System.Collections.Generic”。

using System.Collections.Generic;

I found solution我找到了解决方案

string[] resultArray = Array.ConvertAll(dataArray, x => x.ToString());

After that code works在该代码工作之后

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

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