Question

The language I use is C#.

Say we have a IEnumerable, which is the result of a linq query. T is an anonymous type. What is the best way if we want to access the elements of this type.

I think that there are two ways.

1) Convert the IEnumerable to List and then access the elements.

List<T> list = result.ToList();
for(int rowIndex=0; rowIndex<list.Count; rowIndex++)
{
    double x = list[rowIndex].val;
}

2)

for(int rowIndex=0; rowIndex<result.Count(); rowIndex++)
{
    double x = result.ElementAt(rowIndex).val;
} 

The reason why I am thinking something like the above is that except from accessing the elements of the IEnumerable, I need their indices. In other words, if an element is the first, the second etc.

Thanks in advance for any help !

Was it helpful?

Solution

You don't need to create collection, use an int variable which is 0 and increase it in a foreach. Then you have the index and the element.

int index = 0;
foreach(var x in result)
{
    // x is the element and index the current index
    Console.WriteLine("Val:{0} Index:{1}", x.val, index);
    index ++;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top