Findindex及find中需要一个参数,可用一个Lambda表达式来表示。 Findindex返回查找内容在列表中的位置,find返回参数相同类型的对象。 注意,如果找不到会报错哦,所以最好加上try. 示例如下: 假设有一个list,里面有10组数据,每组数据我都放到一个class中。现在演示一下查找的方法。 以下是用来表示数据的class,其实用struct也是一样的 public class MyInfo { public int age; public double value; public string name; }
代码调用: List <MyInfo> mystr=newList<MyInfo>(); //创建一个存储数据的LIST int []agearray=newint[]{20,30,60,14,16,42,34,45,22,31}; string []names=newstring[]{'A','B','C','D','E','F','G','H','I','J'}; for(int i=0;i<10;i++)//将数据放入LIST中 {MyInfo stem=newMyInfo(); stem.name=names[i]; stem.age=agearray[i]; stem.value=i/3; mystr.Add(stem); } try//防止查找内容不存在的出错 { int iage=mystr.Find(a=>a.name=='C').age;//查找名称为“C“的人的年龄 lbLog.Items.Add('Find people C's age,result: '+iage.ToString());//在listbox(lbLog)中显示 string sname=mystr.Find(a=>a.age==34).name;//查找年龄为34的人名 lbLog.Items.Add('Find the people name whose age is 34,Result: '+sname);//在listbox(lbLog)中显示 int imatch=mystr.FindIndex(a=>a.name=='D');//查找是否存在叫'D'的人,返回list中有位置 lbLog.Items.Add('Find match item is: '+imatch.ToString());//在listbox(lbLog)中显示 } catch { lbLog.Items.Add('Can't find anything!'); }
|