C#中Find及Findindex用法

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=new List<MyInfo>();  //创建一个存储数据的LIST      
            
            int []agearray=new int[]{20,30,60,14,16,42,34,45,22,31};
            string []names=new string[]{"A","B","C","D","E","F","G","H","I","J"};
            
            for(int i=0;i<10;i++)//将数据放入LIST中
            {MyInfo stem=new MyInfo();
                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!");
            }

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值