将foreach循环压缩为linq语句
本文关键字:linq 语句 压缩 foreach 循环 | 更新日期: 2023-09-27 18:28:50
所以我有三个列表:
// Members stores all non-sorted member objects
var Members = new List<Member>();
// Years stores all the expected graduation years I want to compare
var Years = new List<int>();
// Sorted will contain all of the members that have a matching year
var Sorted = new List<Member>();
我使用foreach循环对这些值进行排序
foreach (var m in Members)
{
foreach (var y in Years)
{
if (m.ExpectedGraduationYear == y)
{
Sorted.Add(m);
}
}
}
有没有办法把它压缩成一个linq语句?
您可以使用这样的LINQ查询:
Sorted = (from m in Members
join y in Years
on m.ExpectedGraduationYear equals y
select m).ToList();
Members.Where(m => Years.Contains(m.ExpectedGraduationYear)).ToList()
类似这样的东西:
var Sorted = (from m in Members
from y in Years
where m.ExpectedGraduationYear == y select m).ToList();
是的,类似于以下内容:
Sorted = Members.Where(m => Years.Any(y => y == m.ExpectedGraduationYear)).ToList();
var Sorted = (from m in Members from y in Years.Where(y => m.ExpectedGraduationYear == y)
select m).ToList();