如何从 IEnumerable<> 对象的特定位置获取数据?
How to get data from specific position from IEnumerable<> object?
我想从特定位置获取 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);
上面的错误 line:Cannot 将类型 Employee 隐式转换为 System.Collection.Generic.IEnumerable。
但是我想从 data variable
中的特定位置获取数据只是因为我所有的代码都在处理这个变量 data
.
注意:如果我的位置变量的值大于 0,那么我将从具有该位置的数据变量中查找数据,但如果位置变量 = 0,那么我将 return Ienumerable.
如何做到这一点???
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 的答案,您可以执行以下操作。
您可以使用 Linq
轻松完成此操作
例如,如果您需要获取位置 2 的项目,只需使用 -
data = data.Skip(1).Take(1);
或根据您的查询 -
data = data.Skip(position - 1).Take(1);
if(position > 0)
data = GetDataAt(data,position);
获取数据的位置:
private static IEnumerable<T> GetDataAt<T>(IEnumerable<T> dataItems, int position)
{
yield return dataItems.ElementAtOrDefault(position);
}
我想从特定位置获取 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);
上面的错误 line:Cannot 将类型 Employee 隐式转换为 System.Collection.Generic.IEnumerable。
但是我想从 data variable
中的特定位置获取数据只是因为我所有的代码都在处理这个变量 data
.
注意:如果我的位置变量的值大于 0,那么我将从具有该位置的数据变量中查找数据,但如果位置变量 = 0,那么我将 return Ienumerable.
如何做到这一点???
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 的答案,您可以执行以下操作。
您可以使用 Linq
例如,如果您需要获取位置 2 的项目,只需使用 -
data = data.Skip(1).Take(1);
或根据您的查询 -
data = data.Skip(position - 1).Take(1);
if(position > 0)
data = GetDataAt(data,position);
获取数据的位置:
private static IEnumerable<T> GetDataAt<T>(IEnumerable<T> dataItems, int position)
{
yield return dataItems.ElementAtOrDefault(position);
}