2013-01-21 54 views
10

我有Employee對象列表。我只需要在兩個索引之間選擇兩個員工對象(基於開始和結束變量)。以下代碼工作正常,但它不在LINQ中。什麼是最好的LINQ代碼爲此目的?LINQ獲取列表中兩個索引之間項目的方式

注:我正在尋找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; 
    } 

} 

客戶

List<Employee> searchResult = DatabaseSimulator.GetData("Divisible by 2", 2, 2); 
+2

注意,你不應該總是創造新當您鏈接這些方法時,用'ToList'列出(在'SearchEmployees'中的fe)。這是非常低效的。相反,只需返回查詢並在末尾調用「ToList」。 –

+0

@TimSchmelter你的意思是我需要返回'IEnumerable'而不是'List'? – Lijo

+1

是的。在這種情況下,最好提供帶有/不帶開始和結束索引的SearchEmployees重載。 –

回答

36

可以使用list.Skip(startIndex).Take(endIndex - startIndex)結構。

startIndex:是第一項目的指標來選擇

endIndex:是和最後項指標來選擇

+5

不應該是'Take(endIndex - startIndex + 1)'? – Lijo

+2

@Lijo:這取決於是否要包含邊緣元素。合法的問題也可能是:*不應該是(startIndex + 1)*。 – Tigran

+0

跟着string.substring的方式應該像lijo說的那樣。無論如何,這真是太棒了。謝謝 – Gaspa79

相關問題