user602996
user602996

Reputation:

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#?

Upvotes: 1

Views: 218

Answers (3)

AbdouMoumen
AbdouMoumen

Reputation: 3854

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 :)

Upvotes: 0

dexter
dexter

Reputation: 7203

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();

    }
  }

Upvotes: 0

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

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

Upvotes: 8

Related Questions