【100个 Unity实用技能】| C# 中List 使用Exists方法判断是否存在符合条件的元素对象

在这里插入图片描述

Unity 小科普

老规矩,先介绍一下 Unity 的科普小知识:

  • Unity是 实时3D互动内容创作和运营平台 。
  • 包括游戏开发美术建筑汽车设计影视在内的所有创作者,借助 Unity 将创意变成现实。
  • Unity 平台提供一整套完善的软件解决方案,可用于创作、运营和变现任何实时互动的2D和3D内容,支持平台包括手机平板电脑PC游戏主机增强现实虚拟现实设备。
  • 也可以简单把 Unity 理解为一个游戏引擎,可以用来专业制作游戏

Unity 实用小技能学习

C# 中List 使用Exists方法判断是否存在符合条件的元素对象

在C#的List集合操作中,有时候需要根据条件判断List集合中是否存在符合条件的元素对象

此时就可以使用 List集合的扩展方法 Exists方法来实现

通过Exists判断是否存在符合条件的元素对象比使用for循环或者foreach遍历查找更直接。

public bool Exists(Predicate<T> match);

下面简单用三种数据类型来对Exists方法进行一个简单的例子介绍,看看具体是怎样使用它的。

基础类型

//基础类型
List<int> list1 = new List<int>() {
    
     11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };

var bRet= list1.Exists(t => t == 15);

if (bRet == ture)
   {
    
    
    Console.WriteLine("存在该元素对象");
   }
else
    {
    
    
    Console.WriteLine("不存在该元素对象");
    }

结构体类型

//结构体类型
public class StructTest
{
    
    
    public int Key;//{ set; get; }
    public string Value; //{ set; get; }
}

List<StructTest> List2 = new List<StructTest> {
    
     };

var bRet= testList.Exists(t => t.Key == 25);
if (bRet== ture)
    {
    
    
    Console.WriteLine("存在该元素对象");
    }
else
    {
    
    
    Console.WriteLine("不存在该元素对象");
    }

引用类型

//引用类型
 public class TestModel
    {
    
    
        public int Index {
    
     set; get; }
        public string Name {
    
     set; get; }
    }

List<TestModel> testList = new List<ConsoleApplication1.TestModel>();
 
 if(testList.Exists(t => t.Index == 7))
 {
    
    
    Console.WriteLine("存在该元素对象");
}
else
{
    
    
    Console.WriteLine("不存在该元素对象");
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zhangay1998/article/details/125714374