C# List类常用操作 之 查找

csharp 复制代码
  
//  
//  
//  作者:鸟哥
//  
//  email:xiaoniao2003@gmail.com
//
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization.Formatters;

class Program
{
    class Student
    {
        internal string Name;
        internal int Age;
        internal Student(string n, int a)
        {
            Name = n;
            Age = a;
        }
        
        public override string ToString()
        {
            return "name:"+Name+",age"+Age;
        }
    }
    static void Main()
    {
        List<Student> students = new List<Student>{
            new Student("aa",12),
            new Student("bb",14),
            new Student("ff",16),
            new Student("cc",12),
            new Student("ee",15),
        };
        //是否students中的所有对象的Age都大于10
        bool b=students.All(stu => stu.Age >10);
        Console.WriteLine("All:"+b);

        //是否students中有对象的Age都大于13
        b = students.Any(stu => stu.Age > 13);
        Console.WriteLine("Any:"+b);

        //列表中是否包含某个对象
        b=students.Contains(new Student("bb", 14));
        Console.WriteLine("Contains:"+b);
        b = students.Contains(students[1]);
        Console.WriteLine("Contains:" + b);

        //列表中是否存在Name 是 bb的对象
        b = students.Exists(stu => stu.Name == "bb");
        Console.WriteLine("Exists:" + b);

        //搜索Age为12的所有对象的第一个对象
        Student s=students.Find(stu => stu.Age == 12);
        Console.WriteLine("Find:" + s);

        //搜索Age为12的所有对象的最后一个对象
        s = students.FindLast(stu => stu.Age == 12);
        Console.WriteLine("FindLast:" + s);

        //搜索所有Name为bb 或Age为14的对象,以列表形式返回
        var r=students.FindAll(stu=>stu.Name=="bb"||stu.Age == 14);
        Console.WriteLine("FindAll:" + r.Count);

        //获取Name为bb 或Age为14的所有对象的第一个对象
        int index = students.FindIndex(stu => stu.Name == "bb" || stu.Age == 14);
        Console.WriteLine("FindIndex:" + index);

        index=students.IndexOf(students[1]);
        Console.WriteLine("IndexOf:" + index);


    }
}

运行结果:

All:True

Any:True

Contains:False

Contains:True

Exists:True

Find:name:aa,age12

FindLast:name:cc,age12

FindAll:1

FindIndex:1

IndexOf:1

相关推荐
Ray Liang16 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Scout-leaf4 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530144 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools5 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的5 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21885 天前
.NET 本地Db数据库-技术方案选型
windows·c#
lindexi5 天前
dotnet DirectX 通过可等待交换链降低输入渲染延迟
c#·directx·d2d·direct2d·vortice
qq_454245036 天前
基于组件与行为的树状节点系统
数据结构·c#
bugcome_com6 天前
C# 类的基础与进阶概念详解
c#
雪人不是菜鸡6 天前
简单工厂模式
开发语言·算法·c#