操作"/>
Unity(C#)Linq 操作
- 按照条件查询:from in where select 的用法
// 例如:获取某班级所有男生成绩总和int scoreSum = (from student in classStudentswhere 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];
}// 等等...
更多推荐
Unity(C#)Linq 操作
发布评论