如何从IEnumerable<>中获取特定位置的数据宾语?

时间:2016-04-18 05:56:33

标签: c# linq ienumerable

我希望在不使用IEnumerable的情况下从特定位置获取forloop的元素。

我必须通过Varible从IEnumerable获取元素:

int position;


public class Employee
{
     public int EmployeeId { get; set; }
     public int Skillssetpoints { get; set; }
     public string Name { get; set; }
     public Nullable<System.DateTime> Date { get; set; }
}


int position=2;
IEnumerable<Employee> data = (from c in context.Employee select c);
data = data.ElementAtOrDefault(position); 

上面一行出错:无法将类型Employee隐式转换为System.Collection.Generic.IEnumerable。

但我想从data variable中的特定位置获取数据只是因为我的所有代码都在这个变量data处理。

注意:如果我的位置变量值大于0,那么我将从数据变量中找到具有此位置的数据,但如果位置变量= 0则我将返回Ienumerable。

怎么做???

3 个答案:

答案 0 :(得分:2)

IEnumerable<Employee> data= null;
IEnumerable<Employee> tempList = (from c in context.Employee select c);
if(position==0)
  data = tempList;
else if(position >0)
{
  data = templist.Skip(position -1).Take(1);
}

您收到错误是因为您试图将单个对象存储到IEnumerable类型的变量中。

通过结合Yogi的答案你可以做到以下几点。

答案 1 :(得分:2)

您可以使用Linq

轻松完成此操作

例如,如果你需要在第2位获得项目,只需使用 -

data = data.Skip(1).Take(1); 

或根据您的查询 -

data = data.Skip(position - 1).Take(1); 

答案 2 :(得分:1)

if(position > 0)
   data = GetDataAt(data,position); 

GetDataAt:

private static IEnumerable<T> GetDataAt<T>(IEnumerable<T> dataItems, int position)
{
yield return dataItems.ElementAtOrDefault(position);
}
相关问题