我有一个员工对象列表。我需要在两个索引之间仅选择两个员工对象(基于起始和结束变量)。以下代码可以正常工作,但它不是使用 LINQ。这个目的最好的 LINQ 代码是什么?
注意:我正在寻找链式方法的方法。
CODE
public static class DatabaseSimulator
{
public static List<Employee> GetData(string name, int index, int pageSize)
{
List<Employee> searchResult = new List<Employee>();
List<Employee> employeesSource = SearchEmployees(name);
int start = ((index - 1) * pageSize) + 1;
int end = (index * pageSize);
for (int i = start; i <= end; i++)
{
if (searchResult != null)
{
int listCount = employeesSource.Count;
for (int x = 0; x < listCount; x++)
{
if (x == i)
{
searchResult.Add(employeesSource[x]);
break;
}
}
}
}
return searchResult;
}
private static List<Employee> SearchEmployees(string name)
{
List<Employee> employees = GetEmployees();
return employees.Where(r => r.Name == name).ToList();
}
private static List<Employee> GetEmployees()
{
List<Employee> employees = new List<Employee>();
int i = 0;
for (i = 0; i <= 100; i++)
{
Employee emp = new Employee();
emp.EmpID = i;
if (i % 2 == 0)
{
emp.Name = "Divisible by 2";
}
else if (i % 3 == 0)
{
emp.Name = "Divisible by 3";
}
else if (i % 5 == 0)
{
emp.Name = "Divisible by 5";
}
else if (i % 7 == 0)
{
emp.Name = "Divisible by 7";
}
else
{
emp.Name = "Other -- "+ i.ToString();
}
employees.Add(emp);
}
return employees;
}
}
客户
List<Employee> searchResult = DatabaseSimulator.GetData("Divisible by 2", 2, 2);
ToList
来创建新列表(例如在SearchEmployees
中)。那样很低效。相反,只需返回查询并在最后调用ToList
即可。 - Tim SchmelterIEnumerable
而不是List
吗? - LCJSearchEmployees
的重载版本,包括/不包括起始和结束索引。 - Tim Schmelter