C# List类常用操作 之 查找

  
//  
//  
//  作者:鸟哥
//  
//  email:[email protected]
//
//
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

你可能感兴趣的:(c#,c#)