Unity(C#)Linq 操作

  • 按照条件查询:from in where select 的用法
 // 例如:获取某班级所有男生成绩总和
 int scoreSum = (from student in classStudents
				 where student.gender == "男"  // where:查询条件
				 select student.score).Sum(); // select:选择对象
// 找出班级内所有男生
 boys=(from stud classStudents where stud.gender == "男" select stud).ToList();
  • 随机排序:
// 给集合、数组按照某种类型,随机排序
mlist = mlist.Where(it => it.type == 1).OrderBy(x => Guid.NewGuid()).ToList();
// 按照指定类型,随机取出集合中的某个元素
randomItem = mlist.Where(it => it.type == 1).OrderBy(x => Guid.NewGuid()).First();
  • 判断某集合中是否有满足条件的对象:
// 例如:三班学生中中有没有叫"小明"的同学
// 方式1:
bool result1 = classThreeStudent.Exists(student => student.name == "小明");
// 方式2:建议使用Exists判断,元素多了,Any判断效率不高。
bool result2 = classThreeStudent.Any(student => student.name == "小明");
  • 根据条件查找对象:
// 方式1:
Role xiaoMing = roleList.Find(r => r.name == "小明");

// 方式2:
int index = roleList.FindIndex(r => r.name == "小明");
if (index == -1) {
    
    
    // 没有找到叫小明的角色
} else {
    
    
    Role xiaoMing = roleList[index];
}

// 等等...

猜你喜欢

转载自blog.csdn.net/a0_67/article/details/117120771
今日推荐