Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ way to get items between two indexes in a List

Tags:

c#

linq

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?

Note: I am looking for Method Chain approach

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);
like image 682
LCJ Avatar asked Jan 21 '13 08:01

LCJ


1 Answers

You can use list.Skip(startIndex).Take(endIndex - startIndex) construct.

Where

startIndex : is an index of the first item to select

endIndex : is and index of the last item to select

like image 137
Tigran Avatar answered Oct 16 '22 17:10

Tigran