在List中获取两个索引之间的项的LINQ方法

29

我有一个员工对象列表。我需要在两个索引之间仅选择两个员工对象(基于起始和结束变量)。以下代码可以正常工作,但它不是使用 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);

3
请注意,在链接这些方法时,不应始终使用 ToList 来创建新列表(例如在 SearchEmployees 中)。那样很低效。相反,只需返回查询并在最后调用 ToList 即可。 - Tim Schmelter
@TimSchmelter 您的意思是我需要返回 IEnumerable 而不是 List 吗? - LCJ
1
是的。在这种情况下,最好提供SearchEmployees的重载版本,包括/不包括起始和结束索引。 - Tim Schmelter
1个回答

67
您可以使用 list.Skip(startIndex).Take(endIndex - startIndex) 结构。
其中, startIndex : 是要选择的 第一个 项目的索引 endIndex : 是要选择的 最后一个 项目的索引

12
应该是 Take(endIndex - startIndex + 1) 吗? - LCJ
6
取决于您是否需要包括边缘元素。一个合理的问题也可能是:“难道不应该是(startIndex + 1)吗?” - Tigran
4
按照lijo所说的方式,应该使用string.substring方法。无论如何,这太棒了。谢谢。 - Gaspa79

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接