简体   繁体   English

如何在C#的通用列表中搜索特定值?

[英]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: 在我的mainForm中,我创建3个随机数,并将它们添加为值: 1 3 3 ,结果是:

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#? 如何在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. 因为您有类型参数实现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 :) 希望这可以帮助 :)

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

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