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

相关推荐
宝桥南山6 小时前
GitHub Models - 尝试一下使用GitHub Models
microsoft·ai·微软·c#·github·.netcore
hixiong1239 小时前
C# OpenvinoSharp部署INSID3
开发语言·人工智能·ai·c#·openvinosharp
星辰徐哥9 小时前
Unity C#入门:变量的定义与访问权限(public/private)
unity·c#·lucene
leoufung10 小时前
LeetCode 30:Substring with Concatenation of All Words 题解(含 C 语言 uthash 实现)
c语言·leetcode·c#
hacker70710 小时前
Visual Studio安装教程(C#开发版)
ide·c#·visual studio
SKY -dada10 小时前
Understand 使用教程
开发语言·c#·流程图·软件构建·敏捷流程·代码复审·源代码管理
William_cl13 小时前
【C#/.NET 进阶】ASP.NET 架构与最佳实践:DI 依赖注入(IoC 核心)从入门到避坑
c#·asp.net·.net
武藤一雄13 小时前
WPF:MessageBox系统消息框
前端·microsoft·c#·.net·wpf
武藤一雄13 小时前
WPF进阶:万字详解WPF如何性能优化
windows·性能优化·c#·.net·wpf·.netcore·鲁棒性
xiaogutou11211 天前
2026年历史课件PPT模板选购指南:教师备课效率与精度的平衡方案
开发语言·c#