0
点赞
收藏
分享

微信扫一扫

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


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

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 struct 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("不存在该元素对象");
}

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


举报

相关推荐

0 条评论