简体   繁体   中英

How do I search for a specific value in a generic List in C#?

class MyGenericClass<T> where T : ICompareable
{
  T[] data;

  public AddData(T[] values)
  {
     data = values;
  }
}

In my mainForm, I create 3 random numbers, and add them as values: 1 3 3 , resulting in:

T[] data :  [0]1 
            [1]3 
            [2]3

I want to be able to search for a specific value and have the number of times that value is present in the array returned to me.

How do I do that in C#?

return data.Count(t => t.CompareTo(valueToSearchFor) == 0);

This should work for you:

   public class MyGenericClass<T> where T : IComparable 
   {
    T[] Data;

    public void AddData(T[] values) 
    {
        Data = values;

        var list = Data.ToList();
        object compareWith = new object();
        compareWith = 3;


        int count = list.Where(a=>a.CompareTo(compareWith) == 0).Count();

    }
  }

this can be easily done since you have your type parameter implement IComparable. all you need is this:

internal class MyGenericClass<T> where T : IComparable
{
    private T[] data;

    public void AddData(T[] values)
    {
        data = values;
    }
    public int FindValue<T>(T value)
    {
        return data.Count(v => v.CompareTo(value) == 0);
    }
}

and the call would be something like:

var myClass = new MyGenericClass<int>();
myClass.AddData(new[] {1,2,3,1});
var count = myClass.FindValue(1);

and that should work (worked for me ;) )

Hope this helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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