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 :)
精彩评论