Click here to Skip to main content
15,887,906 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
When we write a query using linq
Then we say
Foreach (var x in query)
{
}
Let's say query has object[0] and object[1] and each object has different field values

What I have tried:

Inside the for each i saw
X.elementAt(0). Fieldvalue but i don't want to specify 0 i want it take the current index of the for each... How can i
do this?  In order to get the correct result and not get the result of object 0 in each time
Posted
Updated 16-Apr-20 10:22am
v3
Comments
Maciej Los 16-Apr-20 16:00pm    
How does look like your query?
Member 14800672 16-Apr-20 23:56pm    
Table has Id1,Id1,Num1,Num2 fields
var query = Table
.GroupBy(x => new { x.Id1, x.Id2 })
.Select(g => new
{
Id1 = g.Key.Id1,
Id2 = g.Key.Id2,
groupedBy = g

})
foreach (var group in query)
{
// number class takes two double values
Number number = new Number(group.num1, group.num2); // i can't get to num1 and num2
}

i tried this but still i have error
group.groupedBy.Select(x=> x.num1)
the error : can't convert from Ienumrable<double> to double
Member 14800672 17-Apr-20 0:10am    
i think i need to do
Number number = new Number(group.groupedBy.First().num1,group.groupedBy.First().num2);

btw what is the benefit of .Select i made in the query? i still can access Id1 and Id2 without it.. in that case i will put group.First().num1 or any other field so when should i put .Select in query?

You do not have indices in a foreach loop, you can use the variable itself:
C#
foreach (var x in query)
{
   // the x variable is the current element
}

// is equivalent to

for (int i = 0; i < query.Count(); ++i)
{
   var x = query[i];
}

If you really need the current index, then you can create a variable and increment it in the loop:
C#
int index = -1;
foreach (var x in query)
{
   ++index;
   // ...
}
 
Share this answer
 
Comments
Member 14800672 16-Apr-20 16:33pm    
As i said query has object[0] which has two fields Id=1,name =name1and it also has object[1] which has Id=2,name=name2
Now when i write
Foreach(var x in query)
{
// i want to store the names
// x. What?
String value += x.
}
phil.o 16-Apr-20 17:04pm    
string currentName = x.name;
BillWoodruff 19-Apr-20 1:26am    
+5
You can't access the "index" of a foreach, because it doesn't necessarily have one - A foreach operates on an iterator, and how that is implemented is down to the collection itself, not the IEnumerable interface that allows a collection to work with foreach

If you need an index, then use a for loop instead of foreach and provide the index yourself.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900