C#:Find

阅读: 评论:0

C#:Find

C#:Find

实例化一个集合

List userCollection = new List();
userCollection.Add(new User(1, “testOne”));
userCollection.Add(new User(2, “testTwo”));
userCollection.Add(new User(3, “testThree”));

方法一

User resultUser = userCollection.Find(
delegate(User user)
{
return user.UserID == 1 && user.UserName.Equals(“testOne”);
});

方法二

User resultUser = userCollection.Find((User user) =>user.UserID == 1 && user.UserName.Equals(“testOne”));

Findindex及find中需要一个参数,可用一个Lambda表达式来表示。

Findindex返回查找内容在列表中的位置,find返回参数相同类型的对象。

注意,如果找不到会报错哦,所以最好加上try.

示例如下:

假设有一个list,里面有10组数据,每组数据我都放到一个class中。现在演示一下查找的方法。

以下是用来表示数据的class,其实用struct也是一样的

public class MyInfo
{
    
    public int age;
    public double value;
    public string name;
    
}
代码调用:

List mystr=new List();  //创建一个存储数据的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.age34).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!”);
            }
————————————————
版权声明:本文为CSDN博主「derek_chen2012」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:

本文发布于:2024-02-03 04:37:51,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170690627148697.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:Find
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23