C# 在列表中的两个索引之间获取项目的 LINQ 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14435066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ way to get items between two indexes in a List
提问by LCJ
I have List of Employee objects. I need to select only two employee objects between two indexes (based on start and end variables). Following code works fine but it is not in LINQ. What is the best LINQ
code for this purpose?
我有 Employee 对象列表。我只需要在两个索引之间选择两个员工对象(基于开始和结束变量)。以下代码工作正常,但不在 LINQ 中。LINQ
为此目的最好的代码是什么?
Note: I am looking for Method Chain
approach
注意:我正在寻找Method Chain
方法
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;
}
}
Client
客户
List<Employee> searchResult = DatabaseSimulator.GetData("Divisible by 2", 2, 2);
采纳答案by Tigran
You can use list.Skip(startIndex).Take(endIndex - startIndex)
construct.
您可以使用list.Skip(startIndex).Take(endIndex - startIndex)
构造。
Where
在哪里
startIndex
: is an index of the firstitem to select
startIndex
: 是要选择的第一个项目的索引
endIndex
: is and index of the lastitem to select
endIndex
: 是要选择的最后一项的索引