使用通用方法的线性搜索算法

发布于 2025-01-28 18:29:15 字数 2615 浏览 5 评论 0原文

我对代码有问题。 我接收 错误CS0311:类型'对象'不能用作通用类型或方法'genericMethods.search(t [],t)'中的类型参数't'。从“对象”到'system.icomable'。

任务: 创建一个控制台应用并编写通用方法,搜索[int search(t [] dataarray,t searchKey)] 使用线性搜索算法搜索数组。

a)方法搜索应将搜索键与数组中的每个元素进行比较,直到搜索键 找到或直到到达阵列的末端。

b)如果找到搜索键,请返回/显示其位置在数组中(即其索引值);否则 返回-1。

c)您需要用随机值填充数组。 (int值 - 10到49之间,双 值在50到99之间,A和Z之间的char值。数组的大小为10。d

)通过将两种类型的阵列传递到它来测试此方法。 (整数数组和字符串数组)显示 生成的值,以便用户知道他/她可以搜索的值。

[提示:use(t:icombaralible)在Where子句中用于方法搜索,以便您可以将方法compareTo()用于 将搜索键与数组中的元素进行比较]

我的代码:

使用系统;

使用System.Collections.generic;

名称空间线性搜索 { 类通用的方法 {

    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




}
}

您能帮我解决这个问题吗?我是C#的新手。

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)'. There is no implicit reference conversion from 'object' to '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.

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.

b) If the search key is found, return/display its location in the array (i.e. its index value); otherwise
return -1.

c) You need to populate the array with random values. ( int values – between 10 and 49, double
values between 50 and 99, char values between a and z). The size of array as 10.

d) Test this method by passing two types of arrays to it. (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]

My code:

using System;

using System.Collections.Generic;

namespace LinearSearch
{
class 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(
quot;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(
quot;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#..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

怎言笑 2025-02-04 18:29:15

而不是声明dataarray对象[]将其声明为iComparable []。您编写了将您的通用类型<代码> t 限制为iComparable的类型约束。 对象不实现iCombarable,因此它不是有效的类型

Instead of declaring dataArray as an object[] declare it as an IComparable[]. You wrote the type constraint limiting your generic type T to IComparable. object does not implement IComparable, so it is not a valid type

佞臣 2025-02-04 18:29:15

幸运的是,我总是为代码编写通用搜索。对于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
}

您必须在文件中导入“ system.collections.generic”。

using System.Collections.Generic;

Lucky me, I always write generic searches for my code. For other search methods with Generics in C#, you can find them here.

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.

using System.Collections.Generic;
怪我闹别瞎闹 2025-02-04 18:29:15

我找到了解决

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

方案后的解决方案

I found solution

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

After that code works

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文