Unity (C#) Linq operation

  • Query by condition: usage of 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();
  • random order:
// 给集合、数组按照某种类型,随机排序
mlist = mlist.Where(it => it.type == 1).OrderBy(x => Guid.NewGuid()).ToList();
// 按照指定类型,随机取出集合中的某个元素
randomItem = mlist.Where(it => it.type == 1).OrderBy(x => Guid.NewGuid()).First();
  • Determine whether there is an object in a collection that satisfies the condition:
// 例如:三班学生中中有没有叫"小明"的同学
// 方式1:
bool result1 = classThreeStudent.Exists(student => student.name == "小明");
// 方式2:建议使用Exists判断,元素多了,Any判断效率不高。
bool result2 = classThreeStudent.Any(student => student.name == "小明");
  • Find objects based on criteria:
// 方式1:
Role xiaoMing = roleList.Find(r => r.name == "小明");

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

// 等等...

Guess you like

Origin blog.csdn.net/a0_67/article/details/117120771